我正在尝试创建一个小型数据编辑器。单击处理程序将在父类别中添加一个子项,如下所示:
methods: {
addBlank: function(parentKey){
var obj = {}
obj.id = Math.floor((Math.random() * 99999) + 1)
obj.name = "New Item"
obj.data1 = 9
obj.data2 = 9
obj.data3 = 9
this.categories[0].children.push(obj)
console.log("New ref is:",obj.id)
console.log(this.$refs) // new $ref is available
console.log("I can't select it",this.$refs[obj.id]) //returns undefined
console.log("But I can select others",this.$refs['4214234']) //this is ok
}
}
Codepen 示例:https://codepen.io/Kay_Wolfe/pen/xJEVRW
当 this.$refs[obj.id]
在那里时,为什么会返回欠定义?
最佳答案
在生成 DOM 元素之前,ref 实际上是不可用的。既然如此,您必须等待直到它存在才能使用它。
通常在 Vue 中,您使用 nextTick这样做。
addBlank: function(parentKey, event){
var obj = {}
obj.id = Math.floor((Math.random() * 99999) + 1) //(actually a uuid generator is used here)
obj.name = "New Item"
obj.data1 = 9
obj.data2 = 9
obj.data3 = 9
this.categories[0].children.push(obj)
this.$nextTick(() => {
console.log("New ref is:",obj.id)
console.log(this.$refs)
console.log("I can't select it",this.$refs[obj.id])
console.log("But I can select others",this.$refs['4214234'])
})
}
这是您的 pen updated .
注意:一个常见的混淆原因是,当您在 addBlank
方法中记录 this.$refs
时,它看起来好像当您在控制台中检查它时,ref 就在那里。然而,事实上并非如此。您正在记录对 refs 对象的引用,当您在控制台中查看它时具有 ref,但是当您从函数中记录它时它还没有引用。 Chrome(可能还有其他浏览器)将显示您记录的引用的当前状态。
关于javascript - Vuejs 动态添加 ref undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406671/