Vue.js中this.$nextTick()

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

案例一:


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

在这里插入图片描述

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

案例二:


<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>
1234567891011121314151617181920212223242526272829

在这里插入图片描述
根据上面的例子可以看出,在方法里直接打印的话, 由于dom元素还没有更新, 因此打印出来的还是未改变之前的值,而通过this.$nextTick()获取到的值为dom更新之后的值

应用场景—滚动裂表

虽然 Vue.js 通常鼓励开发人员沿着“数据驱动”的方式思考,避免直接接触 DOM,但是有时我们确实要这么做。比如一个新闻滚动的列表项。如果在这里需要操作dom, 应该是等待 Vue 完成更新 DOM之后。

一、新闻滚动列表

1、在created函数中获取后台数据;

2、模板引擎中用v-for生成列表项;

3、调用滚动函数,假设该滚动函数式原声方法写的;

4、什么时候开始调用滚动函数比较合适呢?

二、this.$nextTick()

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

Vue.component('example', {
    
    
  template: '<span>{
    
    { message }}</span>',
  data: function () {
    
    
    return {
    
    
      message: 'not updated'
    }
  },
  methods: {
    
    
    updateMessage: function () {
    
    
      this.message = 'updated'
      console.log(this.$el.textContent) // => 'not updated'
      this.$nextTick(function () {
    
    
        console.log(this.$el.textContent) // => 'updated'
      })
    }
  }
})
 
123456789101112131415161718

三、新闻滚动列表中的this.$nextTick()放哪里?

因为数据是根据请求之后获取的,所以应该放到请求的回调函数里面。

四、注意this.nextTick()

this.nextTick(callback),当数据发生变化,更新后执行回调。
this.$nextTick(callback),当dom发生变化,更新后执行的回调。

猜你喜欢

转载自blog.csdn.net/weixin_46071217/article/details/108858859
今日推荐