Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

v-for循环得到的el-button,其动态绑定class未生效

image.png
我想实现初次打开对话框,默认选择中杯,后期点击大杯时,中杯样式去除,大杯加上样式。实现单选
image.png
点击按钮,执行click事件,事件是使得foodAttrChecked数组的末尾元素==item.id
我动态绑定的class条件是
点击的按钮item.id == foodAttrChecked[length-1]时,绑定一个class
首次加载页面时,foodAttrChecked[length-1]==中杯id,中杯被加上了那个class,这个时候是没有问题的,但是我点击大杯时,没有任何变化,class依然是被中杯绑定,大杯并没有绑上,这是我逻辑有问题吗??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

我感觉你的逻辑有点问题。为什么你要一直判断是否和最后一个相等呢?你每点击一次就push或者unshift一次么,这样子是没办法对应关系去判断的,因为你始终都是在和最后一个进行判断
你这个其实可以这么写

<el-button class="mask-sku-item" @click="foodAttrBtn(item)" :class="foodAttrChecked: foodAttrChecked.includes(item.id)" >{{item.name}}</button>
foodAttrBtn(item){
    const index = this.foodAttrChecked.indexOf(item.id);
    if(index>-1){
        this.foodAttrChecked.splice(index,1);
    }else{
        this.foodAttrChecked.push(item.id)
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...