场景:在v-for循环出来的元素中,有时候不同的元素需要绑定包不同的元素,例如按键,按钮之类的元素,需要在循环出来的元素中循环出不同的事件。
例如下图中按不同的按钮要执行不同的指令
解决方案:利用数据中的编号,为不同的按钮绑定不同的事件方法名称,然后在函数中定义出监听事件,然后给不同的事件绑定相应的方法。
数据:
data() {
return {
items: [{
id: '001',
title: '当前电压值',
styl: '220V',
num: '1'
}, {
id: '002',
title: '当前开关状态',
styl: '开',
num: '2'
}]
}
},
模板:
<template>
<div>
<div v-for="item in items" class="block">
<p class="main-word">{{item.title}}:{{item.styl}}</p>
<button id="dianya1" type="button" class="btn btn-info butt" @click="jinggao(item.num)">更新</button>
</div>
</div>
</template>
方法:
methods: {
jinggao(methodsNums){
this[methodsNums]()
},
1() {
alert('电压指令已发出');
},
2() {
alert('状态指令已发出');
}
}
效果:
完整代码:
<template>
<div>
<div v-for="item in items" class="block">
<p class="main-word">{{item.title}}:{{item.styl}}</p>
<button id="dianya1" type="button" class="btn btn-info butt" @click="jinggao(item.num)">更新</button>
</div>
</div>
</template>
<script>
export default {
name: "Zhuangtai",
data() {
return {
items: [{
id: '001',
title: '当前电压值',
styl: '220V',
num: '1'
}, {
id: '002',
title: '当前开关状态',
styl: '开',
num: '2'
}]
}
},
methods: {
jinggao(methodsNums){
this[methodsNums]()
},
1() {
alert('电压指令已发出');
},
2() {
alert('状态指令已发出');
}
}
}
</script>