首先我们需要知道:
Vue是异步渲染
date
改变之后,Dom
并不会立即渲染
$nextTick
会在Dom渲染之后被触发,从而获取最新的Dom
下面先看没有用$nextTick
方法获取刚更新的Dom
<template>
<div>
<button @click="newAdd">新增+</button>
<!-- ------------------------------- -->
<ul ref="uls">
<li v-for="(item, index) in list" :key="index">{{ item }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: [1, 2, 3],
};
},
methods: {
newAdd() {
this.list.push(parseInt(Math.random() * 10));
this.list.push(parseInt(Math.random() * 10));
this.list.push(parseInt(Math.random() * 10));
const u = this.$refs.uls;
console.log(u.childNodes.length);
},
},
};
</script>
呈现的页面如下:ul
下有三个默认子元素li
当点击新增按钮,会向数组中追加三个随机数并立即打印
当前Dom
的子元素长度
当我们点击了新增,页面的确是渲染出了最新的数据,
但是打印出的Dom
子元素长度为3
这里的3
其实是默认的三个元素的长度,而最新追加进去的三个并没有被计算
这时候我们在试试用$nextTick
。
很简单,只是在定义变量和打印的外面包裹上了$nextTick
这个时候再次点击,发现一切正常,没有出现问题
methods: {
newAdd() {
this.list.push(parseInt(Math.random() * 10));
this.list.push(parseInt(Math.random() * 10));
this.list.push(parseInt(Math.random() * 10));
this.$nextTick(() => {
const u = this.$refs.uls;
console.log(u.childNodes.length);
})
},
},