How to get $nextTick of dom in created?

1. How to get dom in created Here I use two methods: one is $nextTick and setTimeout , one is executed after the DOM update cycle, and the other is to convert asynchronous operations

<template>
  <div class="">
    {
   
   { num }}
    <button ref="button" @click="num++">加1</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      num: 1,
    };
  },
  mounted() {},
  methods: {
    arr() {
      console.log("methods 中的钩子函数");
    },
  },
  components: { },
  beforeCreate() {
    console.log("页面a----" + "beforeCreate", this.num); 
  //创建前的阶段 此时data中的数据未  定义不能访问data中的数据

  },
  created() {
    console.log("页面a----" + "created", this.num); 
    // 创建后 最早可以访问data 和 methods中数据的钩子
    this.$nextTick(()=>{
      console.log(this.$refs.button); // 这两种方式都可以拿到dom
    })
    setTimeout(() => {
      console.log(this.$refs.button);
    });
  },
  beforeMount() {
    // 挂载前 指令已经解析完毕内存中已经生产dom树 但是还没有渲染到本地

    console.log("页面a----" + "beforeMount", this.num);
  },
  mounted() {
    // 最早可以操作 dom 的钩子
    console.log("页面a----" + "mounted", this.num);
  },
  beforeUpdate() {
    console.log("页面a----" + "beforeUpdate", this.num);
  },
  updated() {
    console.log("页面a----" + "updated", this.num);
  },
  beforeDestroy() {
    console.log("页面a----" + "beforeDestroy", this.num);
  },
  destroyed() {
    console.log("页面a----" + "destroyed", this.num);
  },
};
</script>

<style lang="scss"></style>

It can be seen from the order of printing that when the created() hook function is executed, the DOM does not actually perform any rendering , and DOM manipulation has no effect at this time, and using this.$nextTick() in created() can wait After the dom is generated, the dom object is obtained, and the value obtained through this.$nextTick() is the value after the dom update

2. This.$nextTick() is a delayed callback executed after the next DOM update loop. Use it immediately after modifying the data, then wait for the DOM to update. It is the same as the global method Vue.nextTick, except that the this of the callback is automatically bound to the instance that called it.

<template>
  <section>
    <h1 ref="hello">{
   
   { value }}</h1>
    <button type="danger" @click="get">点击</button>
  </section>
</template>
<script>
export default {
  data() {
    return {
      value: "Hello World ~",
    };
  },
  methods: {
    get() {
      this.value = "你好世界";
      console.log(this.$refs["hello"].innerText); //  它的结果就不是dom更新后的结果
      this.$nextTick(() => {
        console.log(this.$refs["hello"].innerText); 
        //  在修改数据之后使用 $nextTick,则可以在回调中获取更新后的 DOM,
      });
       setTimeout(() => { 
           console.log(this.$refs["hello"].innerText);
        });
    },
  },
};
</script>

szh

Guess you like

Origin blog.csdn.net/qq_54753561/article/details/122577051
Recommended