如何避免在外部js类文件中使用Vue.set()来保留嵌套对象属性的反应性?

问题描述 投票:0回答:1

我有这个组成部分:

<template>
    <div class="simple-editor">
        {{editor.view.toolbarManager.buttons}}
        <component
            v-for="(button, name) in editor.view.toolbarManager.buttons" 
            :is="button.component" 
            :options="button.options"
            :key="name"
        ></component></div>
//.......................

我正在尝试在editor.view.toolbarManager.buttons循环中使用v-for。 Vue devtools向我展示(在所有3种情况下)editor.view.toolbarManager.buttons是一个对象,并包含4个包含另一个对象的属性。

<script>
export default {
    data: function() {
    return {
        editor: new Editor({
            doc: this.value,
            init: this.init,
        }),
    }
    },

[editor.view.toolbarManager.buttons使用动态导入的脚本在Editor()类的子类中填充:

props.plugins.forEach(plugin => {
    this.plugins[plugin] = import(/* webpackMode: "eager" */ '../plugin/' + plugin);
});

我这样填写editor.view.toolbarManager.buttons

// case 1: works fine as expected
Vue.set(this.buttons, name, {
    component,
    options,
});     

/* case 2: loses vue reactivity
var button = {};

button[name] = {
    component,
    options,
};

Object.assign(this.buttons, button);
*/

/* case 3: loses vue reactivity
this.buttons[name] = {
    component,
    options,
};
*/

下一个问题:当我尝试在模板中渲染{{editor.view.toolbarManager.buttons}}时,情况2和3的对象空了,如下所示:

{}

这意味着vue反应性被破坏。 Editor()是外部类,我不想将其绑定到Vue。 Vue反应性在数组的外部类中很好,因为使用了splice / push方法。是否存在用于保留Vue反应性的对象属性的类似方法?

vue.js vue-reactivity
1个回答
0
投票

哦!我搞砸了Object.assign()。这是使用Object.assign()而不是Vue.set()的权利:

var button = {};

button[name] = {
    component,
    options,
};

this.buttons = Object.assign({}, this.buttons, button);

这对我来说很好。文档在这里https://vuejs.org/v2/guide/reactivity.html#For-Objects

// instead of `Object.assign(this.someObject, { a: 1, b: 2 })`
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
© www.soinside.com 2019 - 2024. All rights reserved.