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

Viewed 11572

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?

2 Answers
  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://composition-api.vuejs.org/api.html#template-refs

You need to pass a value to ref in order to initialize it:

let tabs = ref([tab1, tab2, ...])

console.log(tabs) // tabs.value is now [tab1, tab2, ...]
Related