如何在vue.js中动态设置@click?

时间:2018-09-06 06:44:43

标签: javascript vue.js

我有对象数组,其中动作是vue对象的方法。

如何在v-for循环中动态设置@click

我尝试使用this.m1,“ this.m1”,“ m1”,但出现错误:

  

fns.apply不是函数。

Javascript:

new Vue({
  el: "#app",
  data: {
    items: [
      { title: "Learn JavaScript", action: this.m1 },
      { title: "Learn Vue", action: "m2" },
      { title: "Play around in JSFiddle", action: "this.m3"},
      { title: "Build something awesome", action: "m4"}
    ]
  },
  methods: {
    m1() {
        console.log('1');
    },
    m2() {
        console.log('2');
    },
    m3() {
        console.log('3');
    },
    m4() {
        console.log('4');
    },
  }
})

HTML:

<div id="app">
   <div v-for="item in items">
       <a @click="item.action" href="#">
         {{ item.title }}
       </a>
   </div>
</div>

演示-https://jsfiddle.net/mezhevikin/eywraw8t/338303/

3 个答案:

答案 0 :(得分:1)

data应该是一个函数

new Vue({
  el: "#app",
  data () {
    return {
      items: [
        { title: "Learn JavaScript", action: this.m1 },
        { title: "Learn Vue", action: this.m2 },
        { title: "Play around in JSFiddle", action: this.m3},
        { title: "Build something awesome", action: this.m4}
     ]
    }
  },
  methods: {
    m1() {
        console.log('1');
    },
    m2() {
        console.log('2');
    },
    m3() {
        console.log('3');
    },
    m4() {
        console.log('4');
    }
  }
})

演示https://jsfiddle.net/ojdz0r41/

答案 1 :(得分:1)

如果将方法名称存储在动作属性中,例如action: "m1",则可以通过invokeMethod将这些名称传递给方法(例如"invokeMethod(item.action)")。现在,在此invokeMethod中,您可以通过调用this[methodName]()来调用相关功能-其中this[methodName]相当于说this["m1"]

var app=new Vue({
  el: "#app",
  data: {
    items: [
      { title: "Learn JavaScript", action: "m1" },
      { title: "Learn Vue", action: "m2" },
      { title: "Play around in JSFiddle", action: "m3"},
      { title: "Build something awesome", action: "m4"}
    ]
  },
  methods: {
    invokeMethod(methodName) {
        this[methodName]();
    },
    m1() {
        console.log('1');
    },
    m2() {
        console.log('2');
    },
    m3() {
        console.log('3');
    },
    m4() {
        console.log('4');
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
   <div v-for="item in items">
       <a @click="invokeMethod(item.action)" href="#">
         {{ item.title }}
       </a>
   </div>
</div>

答案 2 :(得分:0)

您需要在单个方法中传递item对象,然后根据需要进行操作。

var app=new Vue({
  el: "#app",
  data: {
    items: [
      { title: "Learn JavaScript", action: "m1" },
      { title: "Learn Vue", action: "m2" },
      { title: "Play around in JSFiddle", action: "m3"},
      { title: "Build something awesome", action: "m4"}
    ]
  },
  methods: {
    callmethod(item) {
        console.log(item.action);
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="app">
   <div v-for="item in items">
       <a @click="callmethod(item)" href="#">
         {{ item.title }}
       </a>
   </div>
</div>