Vuejs动态添加ref未定义

Kay*_*lfe 3 javascript ref vue.js vuejs2

我正在尝试创建一个小型数据编辑器。单击处理程序将在父类别中添加子项目,如下所示:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

Codepen 示例: https: //codepen.io/Kay_Wolfe/pen/xJEVRW

当它存在时,为什么this.$refs[obj.id]回报不足?

Ber*_*ert 7

在生成 DOM 元素之前,引用实际上并不可用。既然如此,你必须等到它存在才能使用它。

通常在 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'])
      })
  }
Run Code Online (Sandbox Code Playgroud)

这是你的笔已更新

注意:造成混淆的一个常见原因是,当您登录this.$refs方法时addBlank,当您在控制台中检查它时,似乎引用就在那里然而事实上,情况并非如此。您正在记录对 refs 对象的引用,当您在控制台中查看它时,该对象具有 ref,但当您从函数中记录它时,它还没有 ref。Chrome(可能还有其他浏览器)将显示您记录的引用的当前状态。