2017-03-24 18 views
0

我試圖在數據中初始化一個空數組,然後從服務器獲取JSON並填充它。Vue:自動填充Observer對象的空陣列

的問題是,數組總是有一個額外的觀察對象,所以當我登錄它,我看到這一點:

empty items array: [ob: Observer]

這裏是一個代碼摘錄:

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); 

     }); 

    }, 

的問題是,當試圖添加一個新的屬性到數組中的對象我得到一個錯誤:

err TypeError: item.$add is not a function

當我調試我se發生它是因爲它將觀察者對象視爲數組的一部分。

這是正常的嗎?我應該檢查$ add是否存在?在視圖中渲染它時呢,Vue會忽略這個對象嗎?

+0

我認爲這是正常的,因爲VueJS使用觀察者的反應性,所以數據對象中的每個項目都附加了observer.Check但是使用瀏覽器控制檯,不使用JsBin http://jsbin.com/qusugoyame/edit?html,js,console,output –

+0

是的,所有正確的,但是有什麼問題? – euvl

+0

什麼應該是$ add方法?它depracated使用$ set –

回答

2

根據你的代碼,你想在你的items對象中設置active屬性爲false。您還想將每個項目的tests屬性中的所有屬性active設置爲false

Vue.js具有反應性,可自動檢測變化,但僅限於對象本身,而非其屬性。對於數組VUE將只檢測由這些方法的變化(更多關於vue.js https://vuejs.org/v2/guide/list.html#ad列表呈遞):

  • 推()
  • 彈出()
  • 移()
  • 不印字()
  • 剪接()
  • 排序()
  • 反向()

但是屬性呢?您可以使用force來查看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); 

,它應該工作。這裏是工作示例:http://jsbin.com/cegafiqeyi/edit?html,js,output(一些使用的ES6功能,不要混淆)

+0

這樣你就失去了'this'上下文。編輯。 –

+0

@JonatasWalker哦,是的,對不起,這都是ES6 – GONG