I'm trying to get a DOM element that is horizontally scrollable and set it's scroll position. However the property doesn't seem to update it's value even if I output it's value in a console.log() immediately after the assignment.
<script setup>
import {ref, watch} from 'vue';
const container = ref();
watch(container, () => {
console.log(container.value.scrollWidth); // Output: 1500
console.log(container.value.scrollLeft); // Output: 0
container.value.scrollLeft = 33;
console.log(container.value.scrollLeft); // ❌ Output: 0, Expected: 33
})
</script>
<template>
<div ref="container"></div>
</template>
FYI, I'm using watch() instead of onMounted() because I don't know what the scroll position should be until after I make a fetch() call in the parent component. The full version of the <script> section is given below, however the above version can be thrown in a vue playground and will run showing the issue.
I've googled this nine ways to Sunday. I can find articles about Vue 2, Vue 3 Options API, or Vue 3 Composition. I am new to Vue and have only ever used Vue 3 Composition API. Either way, all the articles or stack overflow questions seem to be about accessing (reading) DOM elements using template refs, but they don't show how to assign a value to a DOM element property. The above code get's me as far as reading the properties, but when I try to assign a new value to a property that property doesn't get updated.
<script setup lang="ts">
import { ref, watch } from "vue";
import type { ProbeRequest } from "@/types/classes/ProbeRequest";
import type { ProbeRequestStatus } from "@/types/classes/ProbeRequestStatus";
import { buildTracker, getScrollPosition } from "./utils";
interface Props {
probeRequest: null | ProbeRequest;
}
const props = withDefaults(defineProps<Props>(), { probeRequest: null });
const tracker = ref<(ProbeRequestStatus | string)[]>([]);
const trackerContainer = ref();
watch(
() => props.probeRequest,
(probeRequest) => {
tracker.value = probeRequest ? buildTracker(probeRequest) : [];
if (tracker.value.length > 0) {
console.log(trackerContainer.value.scrollWidth);
console.log(trackerContainer.value.scrollLeft);
const scrollLeft = getScrollPosition(
tracker.value,
trackerContainer.value.scrollWidth
);
trackerContainer.value.scrollLeft = scrollLeft;
console.log(trackerContainer.value.scrollLeft);
}
}
);
</script>