1. 程式人生 > >vue給物件新新增屬性,一定要使用Vue.set( target, key, value )這個API來新增

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掌握不夠呀。