相同按钮或类似按钮可以使用v-for语法来实现
<template>
<view class="">
<button
v-for="(item, index) in buttons"
:key="index"
:ref="'btn' + index"
:class="{ active: item.active }"
@click="toggleActive(index)"
>
Button {{ index + 1 }}
</button>
</view>
</template>
<script>
export default{
data() {
return {
buttons: [
{ active: false },
{ active: false },
]
}
},
methods:{
toggleActive(index) {
this.buttons[index].active = !this.buttons[index].active;
console.log(this.$refs['btn' + index]); // Output the reference of click button
}
}
}
</script>
<style>
.active {
color: red;
}
</style>
其中绑定类名,点击按钮触发事件改变类名的值,使其改变文字颜色。点击事件时传递了当前点击的下标,利用下标来修改当前的样式。