Search code examples
vuejs2vuejs3custom-component

How to access refs from app instance in Vue3


In Vue2 it was possible to access refs from the vue instance like so:

vm.$refs.someRef

How can I achieve this in Vue3? Access the refs from outside the app instance i.e from js code.


Solution

  • If you are using options API, it's the same. If you want to use composition API, you pass a ref to the template. It gets a little confusing because there are two different refs one is the attribute in the template (ref="myref") and the other is the function const myref = ref(null)

    When used in the template, the ref value gets updated and can be then accessed via myref.value

    from https://gitlab.com/mt55/maintegrity-fim-web-interface-server/-/jobs/3293032688/artifacts/download

    <script setup>
    import { ref, onMounted } from 'vue'
    
    // declare a ref to hold the element reference
    // the name must match template ref value
    const input = ref(null)
    
    onMounted(() => {
      input.value.focus()
    })
    </script>
    
    <template>
      <input ref="input" />
    </template>
    

    If the ref is needed from outside of the app, it can be accessed through the instance with:

    const app=createApp(App)
    app._instance?.refs
    

    however that only works if the ref is in the App component. For every other component, while the ref is available somewhere in the app object, traversing through the structure is much more complicated.