讨论数量:
<span v-for="(item,index) in btnlist" @click="handleClick(item)">{{item.text}}</span>
data:{
btnlist: [{
"text":"预览",
"type":1
},{
"text":"编辑",
"type":2
}]
},
methods:{
method1(){
//预览
},
handleClick(btn){
let {type} = btn
//根据不同type调不同方法
if(type == 1){
this.method1()
}
}
}
// 修改一下楼上的
data() {
return {
items:[
{
text: '预览',
method: 'preview'
},
{
text: '测试',
method: 'test'
}
],
}
},
methods: {
handleClick(method) {
console.log(method)
if (typeof this[method] == 'function') {
this[method]();
}
},
preview() {
console.log('预览')
},
test() {
console.log('测试')
}
}
测试了一下还可以这样调用
<div v-for="(item, index) in items" :key="`item-${index}`" @click="handleClick(item.method)()">{{item.text}}</div>
...
handleClick(method) {
if (typeof this[method] == 'function') {
return this[method];
}
// 防止出错,函数没有返回值就是 undefined
return () => {}
},
...
<template>
<div>
<button v-for="(item,index) in funs" :key="index" @click="item">按钮{{index}}</button>
</div>
</template>
<script>
export default {
name: 'index',
data(){
return {
funs: []
}
},
methods:{
test1(){
console.log(1);
},
test2(){
console.log(2);
},
test3(){
console.log(3);
},
test4(){
console.log(4);
},
},
created() {
this.funs.push(this.test1)
this.funs.push(this.test2)
this.funs.push(this.test3)
this.funs.push(this.test4)
},
}
</script>
可以类似于这种实现,不知道这个性能怎么样
测试了一下还可以这样调用