I noticed that to make a template ref in Vue 3 composition api <script setup>
, I should make a variable name with the exact same as the ref value.
For example in Vue 3 documentation:
<template>
<div ref="root">This is a root element</div> <--- notice the ref name "root"
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
setup() {
const root = ref(null) <---- and the variable name should be "root" too
onMounted(() => {
console.log(root.value)
})
return {
root
}
}
}
</script>
I was wondering if I can use the ref the way as Vue 2 do, because I have elements whose ref is random string, and it works on Vue 2 by just passing the name on $refs
object.
<div ref="myCustomRefName"></div>
<script>
let myRef = this.$refs["myCustomRefName"]
</script>
But I can't do that since in Vue3, I should similarize the variable name and the ref prop value. Any help will be appreciated.
refs
and access it by key. Refs can be assigned with ref functions to whatever object you need. They are also accessible on getCurrentInstance() but this shouldn't the first choice. – Jacquline<Modal ref="something"/>
and I want to get the modal component dynamically by the ref. It should be like this$modal.open('something')
. For that case, I think I need to get the refs object like Vue 2 did – Guillemette