Lifecycle and Template Refs
Lifecycle and Template Refs#
So far, Vue has been handling all the DOM updates for us, thanks to reactivity and declarative rendering. However, inevitably there will be cases where we need to manually work with the DOM.
We can request a template ref - i.e. a reference to an element in the template - using the special ref attribute:
<p ref="pElementRef">hello</p>
To access the ref, we need to declare and expose a ref with matching name:
Notice the ref is initialized with `null` value. This is because the element doesn't exist yet when `
const pElementRef = ref(null)
setup() {
const pElementRef = ref(null)
return {
pElementRef
}
}