watching vueuse's useElementVisibility changes is not working

965 Views Asked by At

I have a sample project at https://github.com/eric-g-97477-vue/vue-project

This is a default vue project with vueuse installed.

I modified the script and template part of HelloWorld.vue to be:

<script setup>
import { watch, ref } from "vue";
import { useElementVisibility } from "@vueuse/core";

defineProps({
  msg: {
    type: String,
    required: true,
  },
});

const me = ref(null);
const isVisible = useElementVisibility(me);
watch(me, (newValue, oldValue) => {
  console.log("visibilityUpdated", newValue, oldValue);
});
</script>

<template>
  <div ref="me" class="greetings">
    <h1 class="green">{{ msg }}</h1>
    <h3>
      You’ve successfully created a project with
      <a href="https://vitejs.dev/" target="_blank" rel="noopener">Vite</a> +
      <a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>.
    </h3>
  </div>
</template>

and adjusted App.vue so the HelloWorld component could be easily scrolled on or off the screen.

This appears to match the Usage demo code. The primary difference being that I am using <script setup> and the demo code is not. But, perhaps, I need to do things differently as a result...?

The watcher will fire when the app loads and indicates that the HelloWorld component is visible, but it is not. Additionally, regardless if I scroll so the component is visible or not, the watcher does not fire again.

What am I doing wrong?

UPDATE: modified the question based on the discovery that I needed to add ref="me" to the div in the template. Without this, the watcher was never firing.

1

There are 1 best solutions below

0
On

I think maybe you used vueuse's version is old. The current version is v10 and there has a break change update in useElementVisibility. (useElementVisibility updates list and https://github.com/vueuse/vueuse/pull/2551)

You can use useIntersectionObserver(useElementVisibility's underlying Implementation) instead of it or update your vueuse's version.