vue中nextTick理解与使用

<template>
  <div>
    <button @click="handle">添加属性</button>
    <div ref="div">{{change}}</div>
  </div>
</template>

<script>
export default {
  name: "Mine",
  data() {
    return {
      change: "old"
    };
  },
  methods: {
    handle(){
        this.change='new'
        console.log(this.$refs.div.textContent)//old
        // 使用nextTick获取最新的DOM结构,nextTick内部返回的是一个promise
        this.$nextTick(()=>{
            console.log(this.$refs.div.textContent)//new
        })
    },
    // 所以也可以写成下面写法
    async handle() {
      this.change = "new";
      console.log(this.$refs.div.textContent);//old
      //nextTick获取最新的DOM结构,nextTick返回的是一个promise
      await this.$nextTick();
      console.log(this.$refs.div.textContent);//new
    }
  }
};
</script>

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

代码截图:

vue中nextTick理解与使用