4

I have an element

<tbody ref="tbody">
  <tr class="row" :ref="userIndex" v-for="(userData, uid, userIndex) in users" :key="uid">

in my template. I need to access/edit the DOM property like scrollTop, verticalOffset of <tr> element. How can I achieve this?

I have tried to access using this.$refs[userIndex][0].$el but its not working. I can see all the properties in the console but I am unable to access them. However this.$refs.tbody.scrollTop works.

Below is the snap showing console.log(this.$refs)enter image description here

console.log(this.$refs[userIndex]) enter image description here

console.log(this.$refs[userIndex][0]) enter image description here

As you can see when I use this.$refs[userIndex][0] I don't see the DOM properties

nbbk
  • 1,102
  • 2
  • 14
  • 32

2 Answers2

4

A $ref object will only have a $el property if it is a Vue component. If you add a ref attribute to a regular element, the $ref will a reference to that DOM Element.

Simply reference this.$refs[userIndex][0] instead of this.$refs[userIndex][0].$el.

To see the properties of that element in the console, you'll need to use console.dir instead of console.log. See this post.

But, you can access properties of the element like you would any other object. So, you could log the scrollTop, for instance, via console.log(this.$refs[userIndex][0].scrollTop).

thanksd
  • 54,176
  • 22
  • 157
  • 150
  • @nbbk Use console.dir if you want to see the element's properties – thanksd Aug 09 '17 at 15:37
  • It's also worth highlighting that `this.$refs.refName` is always an array. Even if you expect your ref to be a single element, it'll still be in an array. I missed that part and it left me staring at my code for a few minutes. – sr9yar Dec 11 '19 at 17:58
1

I don't think verticalOffset exists. offsetTop does. To console log an Dom element and its property, use console.dir

Open the browser console and run this working snippet:

var app = new Vue({
  el: '#app',
  data: {
    users: {
      first: {
        name: "Louise"
      },
      second: {
        name: "Michelle"
      }
    }
  },
  mounted() {
    console.dir(this.$refs[1][0])
    console.log('property: ', this.$refs[1][0].offsetTop)
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<table><tbody ref="tbody">
  <tr :ref="userIndex" v-for="(userData, uid, userIndex) in users" :key="uid">
  <td>{{userData}}: {{userIndex}}</td>
  </tr>
</tbody>
</table>
</div>
François Romain
  • 13,617
  • 17
  • 89
  • 123