javascript - 在 Nuxt 中使用 ES6 类作为 vuex 存储状态

标签 javascript vue.js vuex nuxt.js es6-class

当我在 nuxt 中的 vuex 存储上设置 ES6 类 时,我收到以下警告:

 WARN  Cannot stringify arbitrary non-POJOs EndPoint

当我使用对象作为状态时,它会在没有警告的情况下工作。

那么我如何在我的州使用ES6类

我的模型:

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));

最佳答案

正如评论中的讨论,在类中添加toJSON方法解决了在客户端设置状态时的问题,但是当在服务器中设置状态时,状态将变为未定义。 因此添加此代码可以解决问题:

    toJSON() {
        return Object.getOwnPropertyNames(this).reduce((a, b) => {
            a[b] = this[b];
            return a;
        }, {});
    }

关于javascript - 在 Nuxt 中使用 ES6 类作为 vuex 存储状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61603040/

相关文章:

javascript - 动态如果在 foreach 绑定(bind)内在 View 中执行 "group by"

javascript - js Tabulator 在复选框选择时触发事件 vue3js

forms - Vue Element UI - 默认 el-input-number 为空字段而不是数字

javascript - 使用 Vuex 进行细粒度组织

javascript - 如何在 Vue 中使过滤列表更具动态性

javascript - pnotify 拒绝工作

javascript - 如何在回调中访问正确的 `this`?

javascript - 使用 ref 访问对象

javascript - [Vue 警告] : Error in render: "TypeError: Cannot read property ' products' of undefined"

javascript - 返回 AngularJS 中两个数组值之间的匹配