繁体   English   中英

Vue.js - 滚动到不工作的元素

[英]Vue.js - Scroll to element not working on

我有以下 v-for,当我添加新评论时,我想滚动到该评论,但我在控制台中收到以下错误:

Cannot read property 'top' of undefined

这是在我的 add 方法中导致错误的行:

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

我检查了控制台并且 response.data.id 不是空的,所以它必须与 jquery 无法识别添加的元素有关。 有任何想法吗?

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

    }
 });    

在尝试使用 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)
})

另请查看https://v2.vuejs.org/v2/api/#Vue-nextTick

您可以使用vue-scrollto为您提供许多选项和兼容性,即使对于 Nuxt.js

给定一个像http://localhost:9104/post/477#entry-1327这样的 url,使用 watch 和计算属性来确保在滚动到元素之前呈现所有数据。

  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)
        })
      }
    }
  },

特殊球

如何使用哈希建立正确的链接

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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