IT이야기

Vue.js - Vuex에 저장된 Javascript 모델이 개체로 변환됨

cyworld 2022. 4. 27. 21:39
반응형

Vue.js - Vuex에 저장된 Javascript 모델이 개체로 변환됨

나는 지금 Vuex와 문제가 있어.내가 하려는 것은, vuex 매장에 자바스크립트 클래스(모델)를 저장해 두는 것이다.내가 다시 그 모델에 접근하기 전까진 이게 효과가 있을 것 같아클래스에서 일반 객체로 자동 변환된다.

다음은 vuex 모듈 JS 파일:

const state = {
  ownedCoins: []
}

const mutations = {
  ADD_COIN (state, coin) {
    console.log(coin)
    state.ownedCoins.push(coin)
    console.log(state.ownedCoins)
  }
}
const actions = {}

const getters = {
  ownedCoins (state) {
    return state.ownedCoins
  },
}

export default {
  state,
  mutations,
  actions,
  getters
}

돌연변이에 있는 두 콘솔 로그는 나에게 정확한 개체를 주지만, 게터를 사용하면 저장된 클래스가 개체로 바뀌었다.

반환해야 할 클래스:

export default class Coin {
  constructor (name, amount, priceBought) {
    this._priceBought = priceBought
    this._name = name
    this._amount = amount
  }

  get name () {
    return this._name
  }

  set name (value) {
    this._name = value
  }

  get amount () {
    return this._amount
  }

  set amount (value) {
    this._amount = value
  }

  get priceBought () {
    return this._priceBought
  }

  set priceBought (value) {
    this._priceBought = value
  }
}

그리고 여기 그 물건을 가게에 맡기고 있다.

const coin = new Coin(
  this.formAdd.coin,
  this.formAdd.amount,
  this.formAdd.price
)

this.$store.commit('ADD_COIN', coin)

참조URL: https://stackoverflow.com/questions/48353971/vue-js-vuex-stored-javascript-model-gets-converted-to-object

반응형