首先有一个环境
整体的代码如下
如果按照下面的逻辑,现在items里面是三个元素,那么当我们新增的时候,ul>li的元素应该是4个
但是当你运行下列代码时,却没有得到想要的结果
因为打印 出来的结果是 3,但是元素却有4个
<template>
<div class="home">
<ul ref='ulRef'>
<li v-for="(item,index) in items" :key='index'>{{item}}</li>
</ul>
<button @click='addItems'>添加</button>
</div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'HomeView',
components: {
HelloWorld
},
data: ()=>({
items: ['apple','banana','watermelon']
}),
methods:{
addItems(){
this.items.push(Math.random())
// 获取元素的个数
const ulElem = this.$refs.ulRef
const length = ulElem.children.length
console.log('length', length);
}
}
}
</script>
那么就需要我们的主角 nextTick
修改一下addItems方法
addItems(){
this.items.push(Math.random())
// 获取元素的个数
this.$nextTick(()=>{
const ulElem = this.$refs.ulRef
const length = ulElem.children.length
console.log('length', length);
})
}
这个时候就得到我们需要的结果了
因为vue的dom是异步更新的,而nextTick的更新时机就在DOM更新完之后的一个节点,所以才能拿到我们所需要的那个结果