Search code examples
javascriptvue.jsvuejs2ref

Vuejs dynamically added ref undefined


I'm trying to create a little data editor. A click handler will add an child item inside a parent category like so:

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 example: https://codepen.io/Kay_Wolfe/pen/xJEVRW

How come this.$refs[obj.id] return underfined when its there?


Solution

  • A ref is not actually available until the DOM element is generated. That being the case, you have to wait until it exists in order to use it.

    Typically in Vue, you use nextTick to do that.

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

    Here is your pen updated.

    Note: one common cause for confusion is that when you log this.$refs in your addBlank method, it appears as though the ref is there when you inspect it in the console. In fact, however, that's not the case. You are logging a reference to the refs object, which at the time you look at it in the console has the ref, but at the time you log it from the function it does not yet have the ref. Chrome (and possibly other browsers) will show the current state of the reference you logged.