vue什么时候才能操作dom?

mounted() {
    this.$refs.index.style.paddingBottom = this.$refs.sus.clientHeight + 'px'
}

试着在mounted声明周期去获取某元素的高度,但是仍然获取到的是0,即使是DOMContentLoad 或者 window.onload 后仍然取不到。

那vue要什么时候才能获取dom的实际计算结果?

阅读 13.7k
8 个回答

就是在mounted的时候,如果你要获取的元素高度是动态由数据撑起来的需要使用this.$nextTick

<div id="app">
    <div id="example">
    <my-component></my-component>
  </div>
</div>
new Vue({
  template: `<h1 ref=test>1</h1>`,
  created: function(){
    console.log('created')
    debugger
  },
  mounted: function(){
    console.log('mounted')
    console.log(this.$refs.test.clientHeight)
    debugger
  }
}).$mount('#app')

可测试上方代码。

this.$nextTick

试试看this.$nextTick

mounted (){
    this.$nextTick(() => {
        this.$refs.index.style.paddingBottom = this.$refs.sus.clientHeight + 'px';
    });
}

不要用$refs去查节点,它不是响应式的。

绑定对应的事件就可以

methods:{
    this.$nextTick(() => {
        this.$refs.index.style.paddingBottom = this.$refs.sus.clientHeight + 'px';
    })
}

this.$nextTick 后可以做,但是为什么要去通过dom获取高度,什么需求,说出来,可能存在不需要操作dom的方法

created的时候,看声明周期就知道了。clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题