vue中v-for循环出来的元素绑定的不同事件

场景:在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>
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值