$nextTick
● Vue 是异步渲染
● data 改变后,DOM不会立刻渲染
● $nextTick 会在 DOM 渲染之后被触发,以获取最新 DOM 节点
先看不用nextTick的情况
<template>
<div>
<button @click="add">添加3项目</button>
<ul ref="ul1">
<li v-for="(x,i) in list" :key="i">{{ x }}</li>
</ul>
</div>
</template>
<script>
export default {
data () {
return {
list: ['a', 'b']
}
},
methods: {
add () {
this.list.push(Date.now())
this.list.push(Date.now())
this.list.push(Date.now())
const ul1 = this.$refs.ul1
// 获取ul1这个dom下有多少子元素
console.log('ul下有多少个子元素', ul1.childNodes.length)
}
}
}
</script>
可以观察到,明显是数不对,这是因为vue是异步渲染的,不是一改变data就立刻去渲染,而是先将所有的改变存起来,然后一次渲染。那我们如何去获知什么时候渲染完成了呢?
用nextTick
<script>
export default {
data () {
return {
list: ['a', 'b']
}
},
methods: {
add () {
this.list.push(Date.now())
this.list.push(Date.now())
this.list.push(Date.now())
this.$nextTick(() => {
const ul1 = this.$refs.ul1
// 获取ul1这个dom下有多少子元素
console.log('ul下有多少个子元素', ul1.childNodes.length)
})
}
}
}
</script>
这就是nextTick的用法。
且注意 ref 的用法。