javascript - Vuejs 动态添加 ref undefined

标签 javascript vue.js vuejs2 ref

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

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/

相关文章:

javascript - 使用 Vue 和 Axios 进行投票按钮

vuejs2 - 如何通过laravel 8惯性中的模型访问关系

javascript - Vuejs + Vuetifyjs + v-text-field 文本转换大写

javascript - 使用 V 形槽激活器激活按钮时出现问题

javascript - 聚焦时显示菜单,失焦或单击菜单以外的内容时隐藏

javascript - 如何使用 angularjs 更新 visjs 的节点或边缘属性?

javascript - 正则表达式 - 替换 HTML 字符串中不包含在 HTML 标记中的文本

javascript - 内联数组注释 DI 与 AngularJS 中的 $routeProvider 不兼容吗?

javascript - Vue - 将插槽传递给子组件

spring-boot - Vue/SpringBoot : Why does my JSESSIONID keeps changing