I have been using Vue 3 template refs in a Nuxt project with the composition API, and so far, they have worked well for other components. However, I am facing an issue where the refs are returning null in this particular case.
Below is the template code:
<template>
<div class="horizontal-scroll-fix" ref="container">
<div class="horizontal-scroll-fix__scroll-fix">
<container class="horizontal-scroll-fix__container">
<div class="horizontal-scroll-fix__viewport" ref="viewport">
<div class="horizontal-scroll-fix__wrapper" ref="wrapper">
<slot></slot>
</div>
</div>
</container>
</div>
</div>
</template>
<script>
import { ref, computed, onMounted, onBeforeUnmount, useSlots } from 'vue';
export default {
setup() {
const container = ref(null);
const wrapper = ref(null);
const viewport = ref(null);
onMounted(() => {
if (process.client) {
console.log(container?.value) // returns undefined
}
});
}
}
</script>
When console.logging the ref object, it shows the following:
RefImpl {__v_isShallow: false, dep: undefined, __v_isRef: true, _rawValue: undefined, _value: undefined}
UPDATE
I have been informed that I need to return the refs at the end of the setup script using
return { container, wrapper, viewport }
. However, what puzzles me is that all other components in my project work fine without needing to do this. What could be different about this one that I am not noticing? Here is an example of another component with template refs that works perfectly without returning the values:
<template>
<container>
<div :class="'sequence sequence--'+section.displayAs">
<div class="sequence__content" ref="content">
// inner content removed for demonstration purpose
</div>
</div>
</container>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
const props = defineProps({
section: {
required:true,
type:Object
}
});
const isDesktop = ref(false);
const currentSectionIndex = ref(0);
const fixedVisual = ref(null);
const content = ref(null);
function initMediaQuery() {
const mediaQuery = window.matchMedia('(min-width:1024px)');
checkDeviceSize(mediaQuery);
mediaQuery.addListener(checkDeviceSize);
};
// More code goes here...
</script>