【问题标题】:Use ES6 classes as vuex store state in Nuxt在 Nuxt 中使用 ES6 类作为 vuex 存储状态
【发布时间】:2020-05-04 23:01:14
【问题描述】:

当我在 nuxt 中将 ES6 类 设置为我的 vuex 商店时,我收到以下警告:

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

【问题讨论】:

  • 你的SET_ENDPOINTS突变有什么作用?
  • 对我的州来说只是新的价值。当然,在询问之前我搜索并看到了,但我不使用 vuex orm。
  • 该问题提到 devalue 的 Nuxt 分叉是警告的来源。您是否尝试过在您的课程中添加 toJSON 方法?
  • 当我添加 toJSON 没有正文的方法时,警告消失了,但是为什么?

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 2022-01-09
    • 2018-05-22
    • 2019-05-26
    • 2020-11-18
    • 1970-01-01
    • 2020-04-08
    相关资源
    最近更新 更多