vue 销毁阶段之前没法获得dom元素宽度

<template>
  <a class="parentA uk-panel uk-panel-hover algo-progress" >
    <slot name="content"></slot>
  </a>
</template>
<script>
  export default{
    init() {
      console.log("init 实例开始初始化:");
      console.log($(".parentA").width());
    },
    created() {
      console.log("created 实例创建后:");
      console.log($(".parentA").width());
    },
    beforeCompile() {
      console.log("beforeCompile:");
      console.log($(".parentA").width());
    },
    compiled() { 
      console.log("compiled:");
      console.log($(".parentA").width());
    },
    attached() {  
      console.log("attached 插入DOM成功:");
      console.log($(".parentA").width());
    },
    ready() { 
      console.log("ready 一切准备好了:");
      console.log($(".parentA").width());
    },
    beforeDestroy() {  
      console.log("beforeDestroy 销毁前:");
      console.log($(".parentA").width());
    },
    destroyed() {   
      console.log("destroyed 已销毁:");
      console.log($(".parentA").width());
    },
    detached() { 
      console.log("detached 删除DOM成功:");
      console.log($(".parentA").width());
    },
  }
</script>

图片描述

阅读 4.5k
2 个回答

试下使用 this.$nextTick()

vue执行和dom渲染应该是两个进程,vue是进程1,dom渲染是进程2,可以用setTimeout新建一个进程获取dom宽度。划个图
vue-1----------->
dom-------------2------->
setTimeout-3-------------3--->
----1-----------2--------3--->

我觉得this.$nextTick()本质和setTimeout应该是差不多,只是nextTick可以监控到vue进程执行情况,更可控一点。

推荐问题