In Vue 2, I'm trying to use a custom event handler that receives arguments from a component and receives the current index (from v-for
) as an argument.
I've found several ways to do this (hat-tip to Vue 2 arguments in inline (in-template) event handler), but they all seem to depend on implementation details of Vue. Here's what I'm trying to do (the commented-out HTML also works):
Vue.component('product', {
template: '<button @click="handleClick">Do Fun Stuff</button>',
methods: {
handleClick: function() {
this.$emit('fun-stuff', 'foo', 'bar');
}
}
});
new Vue({
el: '#app',
data: {
callbackData: '',
items: [1, 2, 3, 4, 5],
message: 'Hello Vue!'
},
methods: {
handleFunStuff: function() {
var argString = Array.prototype.join.call(arguments, ' ');
this.callbackData = this.message + ' - ' + argString;
}
}
});
<div id="app">
<p>{{message}}</p>
<template v-for="(i, index) in items">
<product @fun-stuff="function(stuff, things) { handleFunStuff(index, stuff, things) }">
</product>
<!--
<product @fun-stuff="handleFunStuff(index, arguments[0], arguments[1])">
</product>
-->
<!--
<product @fun-stuff="handleFunStuff.bind(null, index).apply(null, arguments)">
</product>
-->
</template>
<p>{{callbackData}}</p>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
Is there a more proper way to do this in Vue?
Coming from Angular 1, this is possible (since component callback arguments are named) and (in my experience) used commonly.
function(stuff, things) { handleFunStuff(index, stuff, things) }
orhandleFunStuff(index, arguments[0], arguments[1])
approach?