【问题标题】:How can I prevent Vuex from interfering with my class instance?如何防止 Vuex 干扰我的类实例?
【发布时间】:2019-10-18 03:02:25
【问题描述】:

我正在尝试在 Vuex 中存储一个类的实例(来自 ProseMirror 的 EditorState)。这个类从外部看或多或少是不可变的,这意味着每当我想对其进行更改时,我只需将该类的一个新实例放入 Vuex。

因此,我在这里不需要 Vue 的更改跟踪,实际上它似乎会干扰 ProseMirror 的内部工作,所以我想知道是否有一种方法可以将我的对象与 Vue 隔离开来被原子处理。

【问题讨论】:

    标签: javascript typescript vue.js vuex prose-mirror


    【解决方案1】:

    我通过接受this question 上的最佳答案的建议并在将其提供给 Vuex 之前冻结我的类实例来修复它。

    const store = new Store<AppState>({
        state: {
            editor: Object.freeze(editorState), // freeze because Vue reactivity messes it up
            filename: null,
            metadata: {}
        },
        mutations: {
            updateDocument(context, transaction: Transaction) {
                console.log("updateDocument called");
    
                // freeze again
                context.editor = Object.freeze(context.editor.apply(transaction));
            }
        },
        strict: process.env.NODE_ENV === "development"
    });
    

    由于Object.freeze 不是递归的,这对 ProseMirror 的内部工作没有任何影响,但它会阻止 Vue 尝试修改对象。

    【讨论】:

    • 你实现了getter吗? (如果不是,为什么要把它放到 vuex 中?)我尝试了这种方法,但是 vue 浏览器插件在它上面崩溃了(据我所知,由于它很大,而不是因为它被冻结)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多