[Vuejs]-Vue Store Methods inside Array/Object

0👍

If my understanding is correct you want to render a method into a @click from a for-loop?

you can create a helper function to deal with it.

here bindFunction() will take the string button.click and return a function

new Vue({
  el: "#app",
  data: {
        buttons: [
        { click: "toggleA", text: "A" },
        { click: "toggleB", text: "B" },
        { click: "toggleC", text: "C" },
        { click: "toggleD", text: "D" },
        { click: "toggleE", text: "E" }
      ]
  },
  methods: {
  	bindFunction(f) {
      this[f]();
    },
    toggleA() {
      console.log("toggleA");
    },
    toggleB() {
      console.log("toggleB");
    },
    toggleC() {
      console.log("toggleC");
    },
    toggleD() {
      console.log("toggleD");
    },
    toggleE() {
      console.log("toggleE");
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <div v-for="(button, index) of buttons" :key="index">
      <button @click="bindFunction(button.click)">{{button.text}}</button>
    </div>
</div>

Leave a comment