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) => {}); 
        }

    }
 });    

问题评论:

原文地址:

https://stackoverflow.com/questions/47756566/vue-js-scroll-to-element-not-working-on

添加评论