0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That is fine, although my issue is how would I get access of that ref from outside the component (or outside vue). Example, if the above component was used in a Vue app created by createApp(). From that instance of the app, can I access the refs used by components in the app?
as long as it is in the main(first) vue sfc it loads, you can access with app._instance?.refs for the nested objects it's a lot harder, since you need to traverse the structure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.