代码之家  ›  专栏  ›  技术社区  ›  laptou

如何防止Vuex干扰我的类实例?

  •  0
  • laptou  · 技术社区  · 6 年前

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

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

    0 回复  |  直到 6 年前
        1
  •  1
  •   laptou    6 年前

    我采纳了上面答案中的建议,解决了这个问题 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尝试修改对象。