[英]Use ES6 classes as vuex store state in Nuxt
当我在 nuxt 的 vuex 商店中将ES6 class设置为 state 时,我收到以下警告:
WARN Cannot stringify arbitrary non-POJOs EndPoint
当我使用 object 作为 state 时,它会在没有警告的情况下工作。
那么如何在我的 state 中使用ES6 类。
我的model:
export default class EndPoint {
constructor(newEndPoints) {
this.login = newEndPoints.login;
this.status = newEndPoints.status;
}
}
并在这里改变 state:
commit(CoreMutations.SET_ENDPOINTS, new EndPoint(response.data));
使用 object:
const EndPoint = {
endPoints(newEndPoints) {
return {
login: newEndPoints.login,
status: newEndPoints.status
};
}
};
并变异:
commit(CoreMutations.SET_ENDPOINTS, EndPoint.endPoints(response.data));
如评论中的讨论,在 class 中添加toJSON
方法解决了在客户端设置 state 时的问题,但是在服务器中设置 state 时,状态将变为undefined
。 所以添加这段代码解决了问题:
toJSON() {
return Object.getOwnPropertyNames(this).reduce((a, b) => {
a[b] = this[b];
return a;
}, {});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.