본문 바로가기
Study/Vue.js

[Vue.js] class를 만들어 vue객체 사용하기

by haeru 2018. 9. 20.

여기서 class는 html의 class가 아닌 객체지향 프로그래밍의 class임을 말합니다.


아래 코드는 REST API 방식으로 구현하기 위해 만든 디자인 (참고용)



main.js

import Vue from 'vue' import Apifrom './services/ApiCall' Vue.prototype.$api = new Api(new Vue())

ApiCall.js

import axios from 'axios' import apiUrl from './api.call.js' class ApiCall { constructor (vue) { this.apiInfo = apiUrl.data() this.vueInstance = vue } userData (callBack) { this.callApi(callBack, this.apiInfo.Info.user) } changeAnything (callBack, data) { this.apiInfo.change.anything.setUrl(data.id, data.cardId, data.slot) this.apiInfo.change.anything.setConfirmMsg(data.currentFriends, data.changeFriends) this.callApi(callBack, this.apiInfo.change.anything) } callApi (callBack, api) { return new Promise (function(resolve){ resolve(function(){ }) }).then(() => { if (api.confirm) { return this.vueInstance.$confirm({content: api.confirmMsg}) } }).then(() => { return axios(api)

}).then((result) => { this.response = result if (api.successMsg !== undefined) { return this.vueInstance.$alert({content: api.successMsg}) } }).then(() => { if (callBack !== null) callBack(this.response) }).catch((error) => { this.apiCallFailed(error, api.errorMsg) }) } apiCallFailed (error, errorMsg = {}) { if (error === undefined || error.response === undefined ) return false let responseMsg = errorMsg[error.response.status] === undefined ? error.response.data.message : errorMsg[error.response.status] this.vueInstance.$alert({content: responseMsg}) return true; } }export default ApiCall

api.call.js
'use strict'
export default{
  name: 'api.call',
  data () {
    return {
      Info: {
        user: {
          url: process.env.API_URL + '/admin/user,
          method: 'GET'
        }
      },
      change: {
        anything: {
          url: '',
          method: 'PATCH',
          confirm: true,
          confirmMsg: '',
          successMsg: '변경 되었습니다.',
          setUrl: function(id, cardId, slot) {
            this.url = process.env.API_URL + '/admin/user/' + id + '/cards/' + cardId + '/slot/' + slot
          },
          setConfirmMsg: function(currentFriends, changeFriends) {
            this.confirmMsg = '장착중 프렌드: ' + currentFriends + '\n' + '장착할 프렌드: ' + changeFriends +
              '\n이렇게 변경 하시겠습니까?'
          }
        }
      }
    }
  }
}