Reputation: 857
I'm trying to extract the data-reportid
attribute from a parent <tr>
when the user clicks on the <td>
.
HTML
<tr :data-reportid="modifiedRows[index]['id']" v-for="(row,index) in modifiedRows" :key="index">
<td v-html="value" v-for="(value, ind) in row" @click="modalRequest(index, ind, value, rowReportID)" :key="ind">
{{ row[ind] }} <---- i know i can just use 'value', i was experimenting.
</td>
</tr>
VueJS - computed
rowReportID() {
return $(this).parent().data('reportid');
},
When the user clicks, the console reports 'undefined' as the result. The DOM correctly renders the data-reportid
attribute and it contains the correct values, so that's not a factor.
What am I missing here? Please be patient. Mostly PHP background.
Upvotes: 4
Views: 1011
Reputation: 29112
A computed property can only have a single, cached value per Vue instance. In this case you seem to be trying to calculated a value based on the current element. A computed property doesn't have that context.
In general a computed property shouldn't be trying to access the DOM. The DOM is not reactive and won't trigger property updates. Further, the DOM may not exist at the point the property is first evaluated.
I believe in this case the specific problem is that this
will be the Vue instance, not a DOM element, so $(this)
won't match anything. You can try adding some console logging inside rowReportID
to confirm.
Instead of using a computed property you could use a method. To access the DOM node you'd need to get it from the native browser event object, which Vue exposes as $event
:
@click="modalRequest(index, ind, value, rowReportID($event))"
with:
methods: {
rowReportID(event) {
return $(event.target).parent().data('reportid');
}
}
There isn't really any need to use jQuery here, you could do this using native DOM APIs just as easily. jQuery generally isn't required when using Vue.
Further, unless there's a really good reason to grab this attribute from the DOM you should avoid that stage altogether. Instead you can do something like this:
@click="modalRequest(index, ind, value, modifiedRows[index].id)"
Upvotes: 2