2017-07-18 91 views
1

組件的數組索引的數據我需要更新我的VueJS組件陣列的一些數據,通過v-for渲染爲一個列表中的模板。沒有更新

當我更新整個數組時,我發現列表在DOM中更新。但是,如果我僅更新索引,則列表不會更新。

這裏有兩個相關的方法:

methods: { 
    loadOnlyOneIndex: function() { 
    this.data[0] = { 
     title: 'Hello error', 
     slug: 'hello', 
     desc: 'will not work' 
    }; 
    }, 
    loadEverything: function() { 
    this.data = [{ 
     title: 'Hello new title', 
     slug: 'hello', 
     desc: 'this will work' 
    }, { 
     title: 'Hello new title 2 !', 
     slug: 'hello2', 
     desc: 'really work' 
    }]; 
    } 
} 

Here is a fiddle.

+1

https://vuejs.org/v2/guide/list.html#Caveats – thanksd

+0

謝謝,這是真正棘手看到對象更新,但不認爲... – moabi

回答

0

documentation

由於JavaScript的限制,Vue公司無法檢測到以下更改到一個數組:

  1. 當您直接設置的項目與指標,例如vm.items[indexOfItem] = newValue

  2. 當修改所述陣列的長度,例如vm.items.length = newLength

要獲得Vue的反應到一個數組的索引的變化,使用Vue.set() method


在你的情況,你應該在你的loadOnlyOneIndex方法使用Vue.set(this.data, 0, newValue)

Here's a working fiddle.


每Vue的實例也具有經由vm.$set的別名Vue.set方法(其中vm是Vue的實例)。

所以,你也可以在你的loadOnlyOneIndex方法使用this.$set(this.data, 0, newValue)

當使用Single File Components時,或者您沒有直接參考Vue對象時,這會很有幫助。