I am using vue 3 template refs in the composition API as I have done with other components which seem to work fine. However, in this instance, they are returning null.
Here is my template:
<template>
<div ref="container">
<div >
<container >
<div ref="viewport">
<div ref="wrapper">
<slot></slot>
</div>
</div>
</container>
</div>
</div>
</template>
<script>
import { ref, computed, onMounted, onBeforeUnmount, useSlots } from 'vue';
export default { // tried also to use shorthand <script setup> but no luck either
setup() {
const container = ref(null);
const wrapper = ref(null);
const viewport = ref(null);
onMounted(() => {
if (process.client) {
console.log(container?.value) // returns undefined
}
});
}
}
</script>
console.logging the ref object returns the following:
RefImpl {__v_isShallow: false, dep: undefined, __v_isRef: true, _rawValue: undefined, _value: undefined}
CodePudding user response:
You need to return the 3 variables at the end of the setup()
method :
setup() {
...
return {
container,
wrapper,
viewport
}
}
CodePudding user response:
The method setup()
is called at the beginning of the lifespan of the component, just as renderer encounters it. That means that all elements used in the body of the <template>
must be known at the moment that setup()
finishes.
Body of your setup is missing the return of ref
values you wish to use in <template>
. In order to get the expected behavior, you should change your setup()
:
setup() {
const container = ref(null);
const wrapper = ref(null);
const viewport = ref(null);
// callbacks such as onMounted, onBeforeCreate, etc.
return { container, wrapper, viewport };
}