this.$nextTick() 它是一个vue获取dom的方法,就是将回调函数延迟在下次dom更新数据后调用,使用它可以立即获取到更新后的dom节点。
这是在没有使用$nextTick()方法前的代码
<template>
<div>
<ul> <!-- 循环数组 -->
<li ref="add" v-for="a in time" :key="a.index">{{a}}</li>
</ul>
<button @click="add">添加</button> <!-- 点击添加 -->
</div>
</template>
<script>
export default {
data () {
return {
time:['项目','项目','项目','项目',]
}
},
components: {},
methods: {
add(){
this.time.push('项目')
var c = this.$refs.add.length //获取添加数组的长度
console.log(c); //打印出现在的数组长度
}
}
}
</script>
<style scoped>
</style>
添加后打印的数组长度没有即及时的更新![](https://img-blog.csdnimg.cn/933b3598f4c34040a93b2b0a916b0f68.png)
调用$nextTick()
methods: {
add(){
this.time.push('项目')
this.$nextTick(()=>{
var c = this.$refs.add.length //获取数组长度
console.log(c); //将数组长度在次打印
})
}
}
数组长度立即更新
![](https://img-blog.csdnimg.cn/15cbd536360845e09ec32450ffa164a9.png)