Vue 一组按钮 多个绑定方法 该如何写?

Vue.js
有没有vue大佬帮我看看怎么把一号 换成二号的写法, 主要是绑定方法

vue
Leon4055
最佳答案

// 修改一下楼上的
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 () => {}
},
...
2年前 评论
讨论数量: 4
<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()
        }
    }
}
3年前 评论

// 修改一下楼上的
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 () => {}
},
...
2年前 评论
<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>

可以类似于这种实现,不知道这个性能怎么样

2年前 评论
Leon4055 (楼主) 2年前
giao哥

单一出来不行吗

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!