在 Nuxt 中使用 ES6 类 作为 vuex store state
Use ES6 classes as vuex store state in Nuxt
当我在 nuxt 的 vuex 商店中设置 ES6 class 状态时,我得到以下警告:
WARN Cannot stringify arbitrary non-POJOs EndPoint
并且当我使用对象作为状态时,它会在没有警告的情况下工作。
那么我如何在我的状态下使用 ES6 classes。
我的模特:
export default class EndPoint {
constructor(newEndPoints) {
this.login = newEndPoints.login;
this.status = newEndPoints.status;
}
}
并在此处改变状态:
commit(CoreMutations.SET_ENDPOINTS, new EndPoint(response.data));
使用对象:
const EndPoint = {
endPoints(newEndPoints) {
return {
login: newEndPoints.login,
status: newEndPoints.status
};
}
};
并变异:
commit(CoreMutations.SET_ENDPOINTS, EndPoint.endPoints(response.data));
如评论中讨论在class中添加toJSON
方法解决了在客户端设置状态时的问题,但在服务器设置状态时,状态将变为undefined
。
所以添加这段代码解决了问题:
toJSON() {
return Object.getOwnPropertyNames(this).reduce((a, b) => {
a[b] = this[b];
return a;
}, {});
}
当我在 nuxt 的 vuex 商店中设置 ES6 class 状态时,我得到以下警告:
WARN Cannot stringify arbitrary non-POJOs EndPoint
并且当我使用对象作为状态时,它会在没有警告的情况下工作。
那么我如何在我的状态下使用 ES6 classes。
我的模特:
export default class EndPoint {
constructor(newEndPoints) {
this.login = newEndPoints.login;
this.status = newEndPoints.status;
}
}
并在此处改变状态:
commit(CoreMutations.SET_ENDPOINTS, new EndPoint(response.data));
使用对象:
const EndPoint = {
endPoints(newEndPoints) {
return {
login: newEndPoints.login,
status: newEndPoints.status
};
}
};
并变异:
commit(CoreMutations.SET_ENDPOINTS, EndPoint.endPoints(response.data));
如评论中讨论在class中添加toJSON
方法解决了在客户端设置状态时的问题,但在服务器设置状态时,状态将变为undefined
。
所以添加这段代码解决了问题:
toJSON() {
return Object.getOwnPropertyNames(this).reduce((a, b) => {
a[b] = this[b];
return a;
}, {});
}