I was trying to figure out how to access both a v-for
member and the original event data to a bound function on an event in vue.js, but couldn't for the life of me find it in the documentation.
What I want:
<div class="card pickup" v-for="pickup in pickups">
<select v-on:change="locationChanged">
with locationChanged
calling the following method in my vue object:
vuePickup = new Vue({
el: '#pickups',
data: {
pickups: pickups,
},
methods: {
locationChanged: (event, pickup) => {
pickup.newLocation = event.target.value == -1;
}
},
});
which requires access to both the element in question and the object that was bound to that portion of the v-model.
By default, using v-on:change="locationChanged"
calls locationChanged
with the event, and the element can be reached via event.target
but I couldn't find a way to access the pickup
object I was binding the particular element to.
Using v-on:change="locationChanged(pickup)"
instead causes locationChanged
to be called with the model I need, but I then lose the reference to the HTML element in question.
What I ended up doing was setting up a local function in the model itself to forward the values:
v-on:change="e => locationChanged(e, pickup)"
which provides me with the information I need.
However, I feel that this is not the correct approach as a) I couldn't find it in the documentation, and b) it's not the most user friendly.
@Lawless pointed me to an existing question by another user who was wondering more generally how to access the event (as compared to my goal of accessing the event target, i.e. the element that triggered the event), but my question about the idiomatic approach here remains as this is a very basic question (callbacks for enumerated elements) and yet both solutions (mine and the linked question) are not very obvious and not covered in the vue.js manual.
Is there a more idiomatic approach prefered by the vue.js community?