[Vuejs]-How to set DOM Element Property (ScrollLeft) in Vue 3 Using Composition

2👍

So the problem was that on the first render, the container was not being overflowed because there was no content (I’m waiting on tracker.value to be an array with multiple elements; and that is waiting on props.probeRequest to have a value). That means that scrollLeft had to be 0. (It’s worth noting that is also why my contrived example didn’t work because it was never scrollable)

Once the container had content I then needed to wait for it to be rendered before I could assign a value to scrollLeft. So I had to add an await nextTick() (didn’t know that was a thing).

Code now looks like this:

<script setup lang="ts">
import { ref, watch, nextTick } 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<HTMLInputElement | null>(null);

watch(
  () => props.probeRequest,
  async (probeRequest) => {
    tracker.value = probeRequest ? buildTracker(probeRequest) : [];

    await nextTick() // ✅ Here is the magic sauce

    if (trackerContainer.value && 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>

Thanks @tachibana-shin for the inspiration!

1👍

This is not a dom problem i bet your ref='container' is not scrollable:
More: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollLeft

Leave a comment