vue实战--v-for 遍历渲染按钮的两种实现方案(重点:按钮点击事件的绑定技巧)
方案1:method为方法名的字符串核心代码@click="callBack(item.method)"callBack(method) {this[method]();},完整范例<template><div class="mainBox"><p>{{ msg }}</p><buttonv-for="(item, index) in btnL
·
方案1:method为方法名的字符串
核心代码
@click="callBack(item.method)"
callBack(method) {
this[method]();
},
完整范例
<template>
<div class="mainBox">
<p>{{ msg }}</p>
<button
v-for="(item, index) in btnList"
:key="index"
@click="callBack(item.method)"
class="btn"
>
{{ item.label }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
msg: "我会告诉你,你点击了哪个按钮!",
btnList: [
{
label: "新增",
method: "add",
},
{
label: "删除",
method: "del",
},
],
};
},
methods: {
add() {
this.msg = "点击了新增按钮!";
},
del() {
this.msg = "点击了删除按钮!";
},
callBack(method) {
this[method]();
},
},
};
</script>
<style scoped>
.mainBox {
padding: 20px;
}
.btn {
background: #009fe9;
color: #fff;
border: none;
padding: 6px;
width: 100px;
border-radius: 4px;
display: inline-block;
margin-right: 10px;
}
</style>
方案2:method为函数
核心代码
method: () => {
this.add();
},
完整范例
<template>
<div class="mainBox">
<p>{{ msg }}</p>
<button
v-for="(item, index) in btnList"
:key="index"
@click="item.method"
class="btn"
>
{{ item.label }}
</button>
</div>
</template>
<script>
export default {
data() {
return {
msg: "我会告诉你,你点击了哪个按钮!",
btnList: [
{
label: "新增",
method: () => {
this.add();
},
},
{
label: "删除",
method: () => {
this.del();
},
},
],
};
},
methods: {
add() {
this.msg = "点击了新增按钮!";
},
del() {
this.msg = "点击了删除按钮!";
},
},
};
</script>
<style scoped>
.mainBox {
padding: 20px;
}
.btn {
background: #009fe9;
color: #fff;
border: none;
padding: 6px;
width: 100px;
border-radius: 4px;
display: inline-block;
margin-right: 10px;
}
</style>
更多推荐
已为社区贡献26条内容
所有评论(0)