我的组件数量取决于数组数量,因此当我向数组添加新项目时,它应该创建新组件。
当创建新组件时,我想获得它的参考,这就是我有误解的地方。最后添加的组件是undefined
当我试图得到它时。
但是,如果我在一段时间后尝试获取参考,它就会起作用。我猜这是因为异步,但我不确定。
为什么会发生这种情况以及是否有办法避免使用setTimeout
?
<div id="app">
<button @click="addNewComp">add new component</button>
<new-comp
v-for="compId in arr"
:ref="`components`"
:index="compId"
></new-comp>
</div>
<script type="text/x-template " id="compTemplate">
<h1> I am a component {{index}}</h1>
</script>
Vue.component("newComp",{
template:"#compTemplate",
props:['index']
})
new Vue({
el:"#app",
data:{
arr:[1,2,3,4]
},
methods:{
addNewComp:function(){
let arr = this.arr;
let components = this.$refs.components;
arr.push(arr.length+1);
console.log("sync",components.length);
console.log("sync",components[components.length-1])
setTimeout(() => {
console.log("async",components.length);
console.log("async",components[components.length-1])
}, 1);
}
}
})
代码笔链接 https://codepen.io/Halws/pen/VxKjgy