简体   繁体   中英

VueJS jQuery: computed value of parent data attribute undefined

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.

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)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM