mpvue中computed属性里的for循环走坑

	data() {
   
		return {
   
			arr: [1, 2, 3]
		}
	},
    computed: {
   
      sum() 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在v-for循环,如果需要动态绑定class,可以通过computed属性来实现。具体实现方法如下: 1. 首先,在data定义需要绑定的class名称,以及一个包含class名称的数组。 2. 在computed属性,使用map方法遍历数据源,根据需要绑定的条件返回class名称,然后将class名称添加到数组。 3. 在v-for循环,使用v-bind指令将class绑定到computed属性定义的数组上。 举个例子,假设你有一个数组items,你想要在循环动态绑定class,可以按照以下方法实现: ``` <template> <div v-for="(item, index) in items" :key="index" :class="getClass(index)"> {{ item.name }} </div> </template> <script> export default { data() { return { activeClass: 'active', items: [ { name: 'item1', active: true }, { name: 'item2', active: false }, { name: 'item3', active: true }, { name: 'item4', active: false } ], classes: [] } }, computed: { getClass() { return this.items.map((item, index) => { if (item.active) { return this.activeClass } else { return '' } }) } } } </script> <style> .active { color: red; } </style> ``` 在上面的代码,我们在data定义了需要绑定的class名称activeClass,以及一个包含class名称的数组classes。在computed属性,我们使用map方法遍历数据源items,根据需要绑定的条件返回class名称,然后将class名称添加到classes数组。 在v-for循环,我们使用v-bind指令将class绑定到computed属性定义的数组classes上。这样,当item.active为true时,对应的div元素就会应用active这个class,字体颜色变为红色。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值