【发布时间】:2020-11-13 23:00:51
【问题描述】:
我正在使用 Nuxt 框架和 Vuex 来在我的网站中存储数据,但是当我想直接在状态中使用一个类时遇到了麻烦。
模型cart.js 定义如下:
export class Cart {
constructor(ownedID) {
this._created = new Date();
this._lastUpdated = new Date();
this._ownerID = ownedID || 'visitor'
this._items = []
}
getItem (articleNumber) {
console.log(this._items)
}
...
}
还有我商店的模块cart.js
import { Cart } from "~/models/cart";
const state = () => ({
cart: new Cart()
})
const mutations = {
ADD_ITEM(state, newItem) {
console.log(state.cart)
}
}
...
当调用ADD_ITEM(state, newItem) 突变时,缺少getItem(articleNumber) 函数,因此我收到TypeError: state.cart.getItem is not a function 错误。
这是console.log的结果:
__ob__: Object { value: {…}, dep: {…}, vmCount: 0 }
_created:
_item:
_lastUpdated:
_ownerID:
这是我设置的沙盒链接。
有人知道我的问题吗?
谢谢。
【问题讨论】:
-
我已按要求更改了带有沙盒链接的帖子。问题仍然存在。我只是使用 dispatch 来触发一个触发我的突变的动作。
-
根据这篇文章,您不能将类实例放入 vuex 商店 stackoverflow.com/questions/62006376/…
-
您的代码在 Vue/Vuex 中运行良好,但在 Nuxt 中运行良好。由于某种原因,Nuxt 从状态对象中剥离了原型继承信息,这意味着它无法找到该类创建的原型方法。 (在没有 Nuxt 的 Vue/Vuex 中,没有
TypeError和getItem有效。) -
@ggirodda 根据该链接
You can absolutely store class instances in the store state.?
标签: javascript oop nuxt.js vuex