如何防止 Vuex 干扰我的类实例? [英] How can I prevent Vuex from interfering with my class instance?

查看:56
本文介绍了如何防止 Vuex 干扰我的类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to store an instance of a class in Vuex (the EditorState from ProseMirror). This class is more or less immutable from the outside, meaning that whenever I want to make changes to it, I will just put a new instance of the class into Vuex.

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

As such, I do not need Vue's change tracking here, and in fact it actually seems to interfere with the internal workings of ProseMirror, so I was wondering if there was a way that I could isolate my object from Vue so that it is treated atomically.

推荐答案

我根据 this 上的最佳答案中的建议修复了它问题并在将其提供给 Vuex 之前冻结我的类实例.

I fixed it by taking the suggestion from the top answer on this question and freezing my class instance before giving it to 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 尝试修改对象.

Since Object.freeze is not recursive, this doesn't have any effect on the internal workings of ProseMirror, but it discourages Vue from trying to modify the object.

这篇关于如何防止 Vuex 干扰我的类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆