在vue中操作DOM--this.$nextTick()

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

一、新闻滚动列表

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

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

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

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

二、this.$nextTick()

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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'
       })
     }
   }
})

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

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

四、注意this.nextTick()

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

猜你喜欢

转载自www.cnblogs.com/mmzuo-798/p/9318053.html