Vue:空数组自动填充观察者对象

Tom*_*mer 3 javascript vue.js vuejs2

我试图在数据中初始化一个空数组,然后从服务器获取一个 JSON 并填充它。

问题是数组总是有一个额外的 Observer 对象,所以当我记录它时,我看到:

空项目数组:[ ob:观察者]

这是一段代码摘录:

data() {
        return {
            items: []
        }
    },
 created() {
         this.$http.get('/api/menus').then(function (response) {

            console.log('items before', this.items); //THIS LOGS items before: [__ob__: Observer]
             this.items = [].concat(response.body);
            this.items.forEach(function (item) {
              console.log('item', item);

              item.$add('active', false);

              item.tests.forEach(function (test) {
                  test.$add('active', false);
              });
        });

         }).catch(function (err) {
             console.error('err', err);

         });

     },
Run Code Online (Sandbox Code Playgroud)

问题是,当尝试向数组中的对象添加新属性时,出现错误:

错误类型错误:item.$add 不是函数

当我调试时,我看到它发生了,因为它认为观察者对象是数组的一部分。

正常吗?我应该检查 $add 是否存在?在视图中渲染它时,Vue 是否忽略了这个对象?

GON*_*ONG 5

根据您的代码,您希望将对象中的active属性设置itemsfalse. 您还希望将active每个项目的tests属性中的所有属性设置为false.

Vue.js 是响应式的并自动检测变化,但仅针对对象本身,而不是它们的属性。对于数组 vue 只会检测这些方法的变化(更多关于 vue.js 中的列表渲染https://vuejs.org/v2/guide/list.html#ad):

  • 推()
  • 流行音乐()
  • 转移()
  • 取消移位()
  • 拼接()
  • 种类()
  • 逆转()

但是属性呢?您可以使用forcevue 查看数组或对象的深度变化,Vue.set(object, property, value)或者this.$set在任何Vue实例中。

因此,在您的示例中,您可以像这样实现它:

this.items.forEach(function (item, key) {
    console.log('item', item);

    this.$set(this.items[key], 'active', false);

    item.tests.forEach(function (test, testKey) {
        this.$set(this.items[key].tests[testKey], 'active', false);
    }, this);
}, this);
Run Code Online (Sandbox Code Playgroud)

它应该工作。这是工作示例:http ://jsbin.com/cegafiqeyi/edit?html,js,output(使用了一些 ES6 功能,不要混淆)