Reputation: 190
I have this basic setup
<div v-for="n in 4">
<some-component @on-some-event="onSomeEvent(n)"></some-component>
</div>
the on-some-event
is dispatched within some-component
. but I need to know which of these components sent the message. with the setup above, only n
is passed into the method. and the data that the event sends is nowhere.
I'd like to interpolate the function so that the method looks like this
onSomeEvent(n){
return (obj)=>{
console.log(`component ${n} sent ${obj}`);
};
}
but wrapping onSomeEvent
with {{}}
throws a warning: attribute interpolation is not allowed in Vue.js directives and special attributes.
I could just pass the n
index into the component but that seems less elegant because I may not have the ability to modify some-component
I am somewhat new to Vue, so perhaps I am missing some core functionality for this type of thing?
Upvotes: 2
Views: 1542
Reputation: 36
<div v-for="n in 4">
<some-component @on-some-event="onSomeEvent | pass n"></some-component>
</div>
....
filters: {
pass(handler, n) {
return function() {
handler()(n, ...arguments)
}
}
},
methods: {
onSomeEvent() {
console.log(...arguments)
}
}
https://jsfiddle.net/2s6hqcy5/2/
Upvotes: 2
Reputation: 5186
You didn't miss anything, the message is correct, in Vue, you won't be able to use interpolation like that. http://vuejs.org/guide/syntax.html#Interpolations
However, you may want to change how you manage events and pass data between components. In your example, you can just bind the data like this:
<div v-for="n in 4">
<some-component :n="n"></some-component>
</div>
In your component, declare the prop:
Vue.component('some-component', {
props: ['n'],
...
Now, inside each component, you have the n
available like any other property (http://vuejs.org/guide/components.html#Props).
Then when dispatching your event, you can call it like this, with no need for a param:
onSomeEvent()
On the event itself, you can access the n
:
console.log('Component' + this.n + ...)
https://jsfiddle.net/crabbly/mjnjy1jt/
Upvotes: 0