Vue.js-Vuex存储的javascript模型转换为对象
我目前在Vuex上遇到了一个问题。我想做的是,在vuex存储中存储一个javascript类(模型)。这似乎是可行的,直到我再次尝试访问该模型。它会自动从类转换为普通对象 这是相应的vuex模块JS文件:Vue.js-Vuex存储的javascript模型转换为对象,javascript,vue.js,vuex,Javascript,Vue.js,Vuex,我目前在Vuex上遇到了一个问题。我想做的是,在vuex存储中存储一个javascript类(模型)。这似乎是可行的,直到我再次尝试访问该模型。它会自动从类转换为普通对象 这是相应的vuex模块JS文件: const state = { ownedCoins: [] } const mutations = { ADD_COIN (state, coin) { console.log(coin) state.ownedCoins.push(coin) consol
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
}
突变中的两个控制台日志都为我提供了正确的对象,但是当使用getter时,存储的类变成了一个对象
这是应返回的类:
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)
我想这是巴贝尔干的。您使用哪个预设?使用
stage-0
preset和babel polyfill
?我认为您应该只在Vuex中存储普通javascript对象(与在Redux中相同)。Vuex将所有状态安全保存到根节点“状态”。通过这种方式,可以很容易地使用jsonYess来stingefy和初始化状态,但我也注意到原始类是用Vue观察器修饰的。为什么要在该州存储类?这将在保存和重新初始化vuex状态时给您带来问题。将硬币存储为普通对象并在硬币类中创建额外的构造函数以将普通对象转换回硬币类不是更好吗?