javascriptvue.jsvue-componentvuejs3

Vue 3: Why dom ref value is undefined when ref in Vue 3 template


I am using Vue 3 beta version and I am trying to access ref in setup function, My component:

JS(Vue):

const Child = createComponent({
  setup () {
    let tabs = ref()
    console.log(tabs)
    return {}
  },
  template: '<div ref="tabs" >Wow</div>'
})

Demo: https://jsfiddle.net/xkeyLwu4/2/

But the value of tabs.value is undefined. What I am doing wrong here?


Solution

    1. You need to have setup() return a ref with the same name.

    2. You can't log the DOM result until after mounting (onMounted)

    const Child = createComponent({
      setup () {
        let tabs = ref()
        onMounted(() => console.log(tabs.value))
        return { tabs }
      },
      template: '<div ref="tabs" >Wow</div>'
    })
    

    See the docs for more examples: https://vuejs.org/guide/essentials/template-refs.html