vue1和vue2获取dom元素的方法 及 nextTick() 、$nextTick()

vue1.*版本中

在标签中加上el='dom',然后在代码中this.$els.dom这样就拿到了页面元素

例如:<div class='box' el='myBox'>你好</div>

让你好的颜色显示为红色:this.$els.myBox.style.color = 'red'

 

vue2.*版本中

在标签中加上ref='dom',然后在代码中this.$refs.dom这样就拿到了页面元素

例如:<div class='box' ref='myBox'>你好</div>

让你好的颜色显示为红色:this.$refs.myBox.style.color = 'red'

 

注:

可以用 $nextTick 来确保 Dom 变化后再执行一些事情:

<ul ref="nav">
	<li>1</li>
	<li>2</li>
	<li>3</li>
</ul>

this.$nextTick( () => {
	this.$refs.nav.children[0].style.color = 'red';
})

 

vue2.0$nextTick监听数据渲染完成之后的回调函数

vue里面本身带有两个回调函数:

 

  一个是`Vue.nextTick(callback)`,当数据发生变化,更新后执行回调。


  另一个是`Vue.$nextTick(callback)`,当dom发生变化,更新后执行的回调。

 

例子:

<ul id="demo">
    <li v-for="item in list">{{item}}</div>
</ul>

 

new Vue({
    el:'#demo',
    data:{
        list=[0,1,2,3,4,5,6,7,8,9,10]
    },
    methods:{
        push:function(){
            this.list.push(11);
            this.nextTick(function(){
                alert('数据已经更新')
            });
            this.$nextTick(function(){
                alert('v-for渲染已经完成')
            })
        }
    }
})

.

posted @ 2017-10-19 21:59  每天都要进步一点点  阅读(2036)  评论(0编辑  收藏  举报