【问题标题】:Vuejs dynamically added ref undefinedVuejs 动态添加 ref undefined
【发布时间】:2018-12-26 15:33:50
【问题描述】:

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

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] 在那里的时候怎么会返回不足?

【问题讨论】:

  • 既然Math.ceil((Math.random() * 99999) 可以实现同样的功能,为什么还要使用Math.floor((Math.random() * 99999) + 1)?但更多的是你的问题,你怎么知道this.$refs[obj.id] 被定义了?显然不是。当您检查this.$refs 时会显示什么?
  • 您需要等到使用nextTick 实际创建了引用。这是你的笔修好了。 codepen.io/Kradek/pen/bjweMa?editors=1010

标签: javascript vue.js vuejs2 ref


【解决方案1】:

在生成 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'])
      })
  }

这是你的pen updated

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 2018-07-27
    • 2019-03-24
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多