【问题标题】:Why is '$el.clientWidth' equal to 0 when opening a modal? (Vue.js)为什么打开模式时'$el.clientWidth'等于0? (Vue.js)
【发布时间】:2020-06-12 04:18:59
【问题描述】:

所以,我试图在我的 Vue.js 网站中获取模态内部元素的宽度。当模态打开时,当我 console.log 它时宽度为 0,但它显然不是 0,因为当模态打开时元素是可见的。当模式关闭时,控制台会记录一个 > 0 的值。

这是一个 CodePen:https://codepen.io/chataolauj/pen/RwwYxBg?editors=1010

watch: {
    showAdd() {
        console.log(this.$refs.input.$el.clientWidth)
    }
}

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    因为元素的实例化是在mounted 这个生命周期之后,然后你实际上可以得到它的长度。 但showAdd 的变化在mounted 之前。那么实际上你得到了 0。

    根据你的代码,你可以试试这个

    showAdd() {
      setTimeout(()=>{
          console.log(this.$refs.input.$el.clientWidth)
      }, 400)
    }
    

    而且还受动画因素的影响,这个时间是0.3s左右,所以Vue.nextTick不行,用setTimeout(()=>{}, 400)也不错,除非你监听动画事件。

    【讨论】:

    • 这是我对问题所在的一种假设。出于各种原因,我真的不想使用 setTimeout,但如果找不到其他解决方案,我可能最终不得不使用。
    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 2016-05-03
    • 2012-11-11
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    相关资源
    最近更新 更多