<template>
<div>
<div ref="list" v-for="(num, index) in abc" :key="index">{{ num }}</div>
<button @click="clickFN">点我</button>
</div>
</template>
<script>
export default {
name: 'App',
data() {
return { abc: [+new Date()] }
},
methods: {
clickFN() {
this.abc.push(+new Date())
const list = this.$refs.list
console.log(list, list.length)
}
}
}
</script>
<style lang="css" scoped></style>
js的同步异步我知道,vue的dom是异步操作知道,
我想点击按钮的时候,abc数组push最新的时间戳,然后在控制台打印,this.$refs.list.length,但是打印出来每次的length都少一个数
我也会用nextTick来解决这个问题。
我的疑问是:nexttick根据vue官方的解释是,"在下一次 DOM 更新结束后执行其指定的回调",但是页面上已经有新的标签元素了啊,标签元素不也是dom的一部分吗?为什么不使用nexttick的情况下,拿到的length和页面上的元素总数不同呢?我卡在这里了。我自己认为,点击了按钮之后,abc已经push了新数据了,而且新数据产生的标签元素,已经在页面上呈现出来了不是吗?那么为什么拿到的length确实缺少的呢?