vue $el对象数据有时是异步的

当第一次进入页面能拿到offsetTop值,该路由被keep-alive缓存。
切回上一个页面,再点进去后,offsetTop需要一秒后才有值


beforChatWindowOpen(params) {
      this.$nextTick(() => {
        //  offsetTop 一开始为0
        console.log(this.$refs['chatItem' + params.inboxChatData.id][0].$el.offsetTop, '立即的')
        setTimeout(() => {
        //  一秒后有值
          console.log(this.$refs['chatItem' + params.inboxChatData.id][0].$el.offsetTop, '一秒后的')
          this.$refs.inboxScrollBox.scrollTop = this.$refs['chatItem' + params.inboxChatData.id][0].$el.offsetTop
        }, 1000)
        this.chatWindowOpen(params.inboxChatData)
      })
    }

图片描述

阅读 1.5k
1 个回答

$nextTick()Usage:

Defer the callback to be executed after the next DOM update cycle. Use it immediately after you’ve changed some data to wait for the DOM update. This is the same as the global Vue.nextTick, except that the callback’s this context is automatically bound to the instance calling this method.

我的理解是在nextTick里执行的语句都是dom刷新后的,所以问题不在这里
很有可能是$el没有取到
你把以下这些都打印出来看看哪一步错了

params.inboxChatData.id
this.$refs['chatItem' + params.inboxChatData.id]
this.$refs['chatItem' + params.inboxChatData.id][0].$el
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题