vue給對象新添加屬性,一定要使用Vue.set( target, key, value )這個API來添加


this.tagList = [{
        id:1,
        tagName:'90后'
      },
      {
        id:2,
        tagName:'土豪'
      },
      {
        id:3,
        tagName:'美女'
      },
      {
        id:4,
        tagName:'帥哥'
      },
      {
        id:5,
        tagName:'鴿子王'
      },
      {
        id:6,
        tagName:'人傻錢多'
      }]

 

今天做一個這樣的功能:遍歷對象數組 tagList 渲染出標簽列表,以前寫過類似的功能,但這次不一樣,tagList的數組項中沒有表示選中狀態的屬性select,我自己后面遍歷添加的:

this.tagList.forEach((item,index)=>{
    item.select = false
})

 

   點擊標簽切換選中狀態,動態添加class,

/* 渲染列表,動態添加class */
<
ul class="tag_list"> <li v-for="(item, index) in tagList" @click="selectTag(index)" :class="{'select': item.select}">{{item.tagName}}</li> </ul>
// 點擊事件
selectTag(index){
this.tagList[index].select = !this.tagList[index].select; }

點擊每個標簽,屬性值select確實是變了,但是綁定的class名紋絲不動,這時我就慌了。

搞了半天終於搞好了,原來是這樣的:

向響應式對象中添加一個屬性,並確保這個新屬性同樣是響應式的,且觸發視圖更新。它必須用於向響應式對象上添加新屬性,因為 Vue 無法探測普通的新增屬性 (比如 this.obj.newProperty = 'hi')

官方文檔:https://cn.vuejs.org/v2/api/#Vue-set

所以給對象添加屬性應該這樣寫:

<script>
    import Vue from 'vue'
    export default{
        data(){
        },
        methods:{
            this.tagList.forEach((item,index)=>{
                 // item.select = false //這是錯誤寫法
                 Vue.set(item,'select',false); //正確姿勢
             }
         }
      }
</script>

然后就完美實現了,哎,這么一個簡單的功能搞了這么久,還是對官方API掌握不夠呀。

 

 

2019/1/22日補充:

今天又遇到了類似的問題,這次是給二元數組添加新的數組元素,寫法如下:

假設:this.tagList = [[5, 8], [3, 1]]

Vue.set(this.tagList, 2, ['a', 'b']) // [[5, 8], [3, 1], ['a', 'b']]

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM