[Vuejs]-Injecting a variable from v-for into a value for on-click

0👍

âś…

Vue has complete control over the HTML generated for a Vue component, and in many situations parts of the template will be regenerated by Vue (in response to things like v-if, v-for etc), so you can’t really use “classic” onclick function handlers, you must use v-on to call a method defined within the component. From inside that method you can then call any global function you want.

function external(item) {
  alert('You clicked ' + item);
}

new Vue({
  el: '#app',
  data: {
    items: ['apple', 'banana', 'orange'],
  },
  methods: {
    internal(item) {
      // Delegate to external function
      external(item);
    },
  },
});
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>

<div id="app">
  <button v-for="item of items" @click="internal(item)">{{ item }}</button>
</div>

Leave a comment