![](/img/trans.png)
[英]Vue cannot get refs on mounted on nextTick after dynamically importing the component?
[英]How to get updated $refs on dynamically created component in Vue?
我的組件數量取決於數組數量,所以當我向數組添加新項目時,它應該創建新組件。
創建新組件時,我想獲得它的參考,這就是我誤解的地方。 當我嘗試獲取它時,最后添加的組件是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);
}
}
})
ref
和$refs
不是反應式的。
如果你想獲取更新的值,你應該等到下一個渲染周期更新 DOM。
而不是setTimeout
你應該使用Vue.nextTick()
:
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])
Vue.nextTick(() => { // changed here
console.log("async",components.length);
console.log("async",components[components.length-1])
}); // changed here
}
}
})
這不是“黑客”,這是正確的做法。 來自官方 API 文檔:
Vue.nextTick([回調,上下文])
論據:
{Function} [callback]
{Object} [context]
用法:
推遲在下一個 DOM 更新周期后執行的回調。 在您更改一些數據以等待 DOM 更新后立即使用它。
// modify data vm.msg = 'Hello' // DOM not updated yet Vue.nextTick(function () { // DOM updated }) // usage as a promise (2.1.0+, see note below) Vue.nextTick() .then(function () { // DOM updated })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.