Vue2中this.$nextTick()的使用和验证执行顺序

Vue2中this.$nextTick()的使用和验证执行顺序

作用:this.$nextTick()在页面交互,尤其是从后台获取数据后重新生成dom对象之后的操作,具有优势。

1、官网释义
1.1、nextTick

链接-https://v3.cn.vuejs.org/api/global-api.html#nexttick

将回调推迟到下一个 DOM 更新周期之后执行。在更改了一些数据以等待 DOM 更新后立即使用它。

import { createApp, nextTick } from 'vue'

const app = createApp({
  setup() {
    const message = ref('Hello!')
    const changeMessage = async newMessage => {
      message.value = newMessage
      await nextTick()
      console.log('Now DOM is updated')
    }
  }
})
1.2、$nextTick

链接-https://v3.cn.vuejs.org/api/instance-methods.html#nexttick

  • 参数:

    • {Function} [callback]
  • 用法:

    将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。它跟全局方法 nextTick 一样,不同的是回调的 this 自动绑定到调用它的实例上。

  • 示例:

createApp({
  // ...
  methods: {
    // ...
    example() {
      // 修改数据
      this.message = 'changed'
      // DOM 尚未更新
      this.$nextTick(function() {
        // DOM 现在更新了
        // `this` 被绑定到当前实例
        this.doSomethingElse()
      })
    }
  }
})
2、需求场景

假设我们更改了某个dom元素内部的文本,而这时候我们想直接打印出这个被改变后的文本是需要dom更新之后才会实现的,也就好比我们将打印输出的代码放在setTimeout(fn, 0)中;

效果

在这里插入图片描述

实例1

index.vue

<template>
  <section>
    <div ref="hello">
      <h1>Hello World ~</h1>
    </div>
    <el-button type="danger" @click="get">点击</el-button>
  </section>
</template>
<script>
  export default {
    methods: {
      get() {
      }
    },
    mounted() {
      console.log(333);//2、加载后
      console.log(this.$refs['hello']);
      this.$nextTick(() => {
        console.log(444);//4、数据更新后
        console.log(this.$refs['hello']);
      });
    },
    created() {
      console.log(111);//1、加载前
      console.log(this.$refs['hello']);
      this.$nextTick(() => {
        console.log(222);//3、数据更新前
        console.log(this.$refs['hello']);
      });
    }
  }
</script>

打印执行顺序

在这里插入图片描述

根据打印的顺序看到:

在created()钩子函数执行的时候DOM 其实并未进行任何渲染,而此时进行DOM操作并无作用,而在created()里使用this.$nextTick()可以等待dom生成以后再来获取dom对象

实例2

效果

在这里插入图片描述

index.vue

<template>
  <section>
    <h1 ref="hello">{{ value }}</h1>
    <el-button type="danger" @click="get">点击</el-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);//dom更新后
        });
      }
    },
    mounted() {
    },
    created() {
    }
  }
</script>

打印验证可以看出:

在方法里直接打印的话, 由于dom元素还没有更新, 因此打印出来的还是未改变之前的值,而通过this.$nextTick()获取到的值为dom更新之后的值

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值