1. Obtain a single Dom instance
Expose root in the render context and bind it to the div as its ref with ref=”root”. In the virtual DOM patching algorithm, if the REF key of a VNode corresponds to the REF in the rendering context, the corresponding element or component instance of a VNode will be assigned to the value of that REF. This is done during the virtual DOM mount/patch process, so the template reference only gets assigned after the initial rendering.
The Refs used as templates behave like any other ref: they are reactive and can be passed into (or returned from) composite functions.
<template>
<div ref="root">This is a root element</div>
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
setup() {
const root = ref(null)
onMounted(() = > {
// DOM elements will be assigned to ref after initial rendering
console.log(root.value)
this is the root element
})
return {
root
}
}
}
</script>
Copy the code
2. Obtain multiple Dom instances
<template>
<div v-for="(item, i) in list" :ref="el => { if (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 ref before each update
onBeforeUpdate(() = > {
divs.value = []
})
return {
list,
divs
}
}
}
</script>
Copy the code
3. Listen for template references
Listening for changes to template references can replace the lifecycle hooks demonstrated in the previous example.
But a key difference from lifecycle hooks is that the Watch () and watchEffect() side effects run before the DOM is mounted or updated, so the template reference has not yet been updated when the listener runs the side effect.
Therefore, listeners that use template references should be defined with the Flush: ‘POST’ option, which will run side effects after DOM updates, ensuring that template references are in sync with the DOM and refer to the correct elements. This will run the side effects after the DOM is updated and ensure that the template references are in sync with the DOM and refer to the correct elements.
<template>
<div ref="root">This is a root element</div>
</template>
<script>
import { ref, watchEffect } from 'vue'
export default {
setup() {
const root = ref(null)
watchEffect(() = > {
console.log(root.value) // => <div></div>
},
{
flush: 'post'
})
return {
root
}
}
}
</script>
Copy the code