uniapp,v-for生成的列表,如何动态更新样式?

新手上路,请多包涵

题目描述

我使用的是uniapp,想要实现点击v-for生成的某个列表项之后,改变该列表项中icon的颜色(或icon类型)
但是试了两种方法都不奏效
第一种不知道是什么原因,点击后inWatch的值改变了,但是样式并没有变
使用第二种方法时,我不知道该怎样获取到被点击元素下的icon子元素,firstElementChild并不被支持

相关代码

<view v-if="allPairList.length > 0" v-for="(pair,index) in allPairList" :key="index" class="item">  
    <view class="row1">  
         <button type="" :data-index="index" @click="switch($event,pair.inWatch)">  
              <uni-icons type="star-filled" :class="{active: pair.inWatch}" :color="pair.inWatch?'#ffaa00':'#999'" size="25" />   
         </button>  
    </view>  
</view>  

<script>  
data(){  
     return{  
           allPairList :[{  
                  name: '123',  
                  inWatch : false    
            }]  
     }  
}  
methods:{  
        switch(e, inWatch){  
        let elIndex = e.currentTarget.dataset.index  
            this.allPairList[elIndex].inWatch = ! this.allPairList[elIndex].inWatch     // 用这种方法可以改变inWatch属性的值,但icon的样式没变   
                e.currentTarget.firstElementChild.color = '#7e2c3a'             // 改用这种方法会报错,firstElementChild无法获取到uni-icon这个元素  
            console.log('点击了第'+elIndex+'个,pair = '+ this.allPairList[elIndex].inWathc)  
         }  
}  
</script> 
阅读 4.2k
1 个回答

vue环境中,更改 data,但是视图没有更新,那说明你是直接更改了 data 中数组或者对象的属性。解决方法是深拷贝赋值或者用 this.$set

还有你这用了vue,还用 data-xxx,代码质量有待提高。

<template
  v-if="allPairList.length"
  v-for="(pair, index) in allPairList"
  :key="index"
  class="item"
>
  <template class="row1">
    <button @click="switch(index, pair.inWatch)">
      <uni-icons
        type="star-filled"
        :class="{ active: pair.inWatch }"
        :color="pair.inWatch ? '#ffaa00' : '#999'"
        size="25"
      />
    </button>
  </template>
</template>

<script>
export default {
  data() {
    return {
      allPairList: [
        {
          name: '123',
          inWatch: false
        }
      ]
    }
  },
  methods: {
    switch(index, inWatch) {
      this.allPairList[index].inWatch = !this.allPairList[index].inWatch
      // $set
      this.$set(this.allPairList, index, this.allPairList[index])
      // or
      // this.allPairList = Object.assign([], this.allPairList)
    }
  }
}
</script>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题