Using the Vue.js 2 api-composition, you have a .ref
attribute on the setupContext
argument of setup()
. As stated in many articles and in this thread : https://github.com/vuejs/composition-api/issues/226 it will NOT be available in vue.js 3, and you should declare attributes of the same name as the ref-ed element :
<div ref='name'/>
setup() {
return {
name : ref(null)
}
}
However, what about when you do not know the ref name at the setup()
?
Like this "minimum" example :
<div v-for="e in elements" @click="elements.push({name:Math.random(), content:Math.random()})">
<div :ref="e.name">e.content</div>
</div>
setup(){
return {
a_function_called_later(){
// I can use this.$refs but is there a more "vuejs3" way to do it ?
}
// ...???
}
}
I had the same problem and was asking in the Vue.js Discord about it. Luckily Carlos Rodrigues could help me out.
<template>
<div v-for="(item, i) in list" :ref="el => { divs[i] = el }">
{{ item }}
</div>
</template>
<script>
import { ref, reactive, onBeforeUpdate } from 'vue'
export default {
setup() {
const list = reactive([1, 2, 3])
const divs = ref([])
// make sure to reset the refs before each update
onBeforeUpdate(() => {
divs.value = []
})
return {
list,
divs
}
}
}
</script>
You can read more about it in the official documentation: https://composition-api.vuejs.org/api.html#template-refs or on my blog: https://markus.oberlehner.net/blog/refs-and-the-vue-3-composition-api/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With