adam78
adam78

Reputation: 10068

Vue.js - Scroll to element not working on

I have the following v-for and when i add a new comment I want to scroll to that comment but I'm getting the following error in console:

Cannot read property 'top' of undefined

This is the line causing the error in my add method:

$('html, body').animate({scrollTop: $("#comment-" + response.data.id).offset().top}, 2000);

I've checked console and response.data.id is not empty so it must be to do with jquery not recognising the added element. any ideas?

<ul class="list-inline">
   <li v-for="(comment, index) in comments" 
       :key="comment.id" 
       :id="'comment-' + comment.id">
     <span v-html="comment.comment"></span>
    </li>
</ul>

 var vm =  new Vue({
    el: '#root',
    data: {
       comments: [
                {
                  "id": 2,
                  "comment": "blah...",
                },
                {
                  "id": 4,
                  "comment": "blah...",
                }
                {
                  "id": 6,
                  "comment": "blah...",
                }
        ]
     },
     methods: {
        add: function (comment) {
             axios.post("api/comments/add, { comment: comment })
               .then((response) => {
                  this.comments.push(response.data);
                  $('html, body').animate({scrollTop: $("#comment-" + response.data.id).offset().top}, 2000);

                })
               .catch((error) => {}); 
        }

    }
 });    

Upvotes: 0

Views: 7681

Answers (2)

user1497119
user1497119

Reputation: 473

You might want to wait until its rendered on the page before trying to manipulate the Object with jQuery.

// next line adds it into the shadow dom
this.comments.push(response.data)
// next tick is called after rendering
this.$nextTick(() => {
  $('html, body').animate({scrollTop: $("#comment-" + response.data.id).offset().top}, 2000)
})

Also check out https://v2.vuejs.org/v2/api/#Vue-nextTick

Upvotes: 3

Igor Parra
Igor Parra

Reputation: 10348

You can use vue-scrollto that gives you many options and compatibility, even for Nuxt.js

Given an url like http://localhost:9104/post/477#entry-1327 use a watch and a computed property to assure all data is rendered before scroll to the element.

  watch: {
    render (n) { // computed prop (bool) that tells me when all api data is already loaded
      const hash = location.hash.substr(1)
      if (!hash) return
      if (n) {
        this.$nextTick(() => {
          var el = document.getElementById(hash)
          this.$scrollTo(el)
        })
      }
    }
  },

Special ball

How to build a proper link with a hash

this.$router.push({ name: 'post', params: { postId }, hash: `#entry-${parentId}` })

Upvotes: 0

Related Questions