vue中使用this.$nextTick()函数

vue中使用nextTick()函数
Vue中nextTick()的使用

Vue 中的 nextTick 涉及到 Vue 中 DOM 的异步更新

Vue 实现响应式并不是数据发生变化之后 DOM 立即变化,而是按一定的策略进行 DOM 的更新。

$nextTick 是在下次 DOM 更新循环结束之后执行延迟回调,在修改数据之后使用 $nextTick,则可以在回调中获取更新后的 DOM,API 文档中官方示例如下:

new Vue({
  // ...
  methods: {
    // ...
    example: function () {
      // modify data
      this.message = 'changed'
      // DOM is not updated yet
      this.$nextTick(function () {
        // DOM is now updated
        // `this` is bound to the current instance
        this.doSomethingElse()
      })
    }
  }

demo:

<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() {
      }
    },
    created() {
      console.log(111);
      console.log(this.$refs['hello']);
      this.$nextTick(() => {
        console.log(222);
        console.log(this.$refs['hello']);
      });
    }
    mounted() {
      console.log(333);
      console.log(this.$refs['hello']);
      this.$nextTick(() => {
        console.log(444);
        console.log(this.$refs['hello']);
      });
    },
  }
</script>

可以看见结果输出顺序:由生命周期,先执行created,再执行mounted,而this. n e x t T i c k ( ) 方 法 在 修 改 数 据 之 后 会 立 即 被 使 用 , 但 需 要 等 待 D O M 更 新 循 环 之 后 , 才 执 行 , 所 以 当 D O M 更 新 完 毕 后 , 先 输 出 222 , 再 输 出 444 。 根 据 t h i s . nextTick()方法在修改数据之后会立即被使用,但需要等待DOM更新循环之后,才执行,所以当DOM更新完毕后,先输出222,再输出444。根据this. nextTick使DOMDOM222444this.nextTick函数的特点。我们一般是处理接口数据时使用它,通过它获取到的数据都是更新后的最新数据。
在这里插入图片描述
demo2:

<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);
        this.$nextTick(() => {
          console.log(this.$refs['hello'].innerText);
        });
      }
    },
    mounted() {
    },
    created() {
    }
  }
</script>

打印结果:先hello world,再‘你好啊’。虽然get函数第一步操作就将this.value重新赋值。但此时DOM还未更新,元素的内置数据还是未改变之前的值。而通过this.$nextTick()获取到的值为dom更新之后的值。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值