Open2

Intersection Observerをvueでコンポーネント化してうまいことしたい(前途

雨東風ぬめちゃ雨東風ぬめちゃ

コンポーネント本体

<template>
  <div :ref="elementId"></div>
</template>

<script>
export default {
  name: "IntersectionObserver",
  props: {
    elementId: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      isIntersectingElement: false,
    };
  },
  watch: {
    isIntersectingElement: function (value) {
      this.$emit("on-intersection-element", value);
    },
  },
  mounted() {
    const element = this.$refs[this.elementId];
    const handler = (entries) => {
      if (entries[0].isIntersecting) {
        // 一度きり動けばok
        this.isIntersectingElement = true;
      }
    };
    const options = {
      rootMargin: '-150px 0px'
    }
    const observer = new window.IntersectionObserver(handler, options);
    observer.observe(element);
  },
};
</script>

使う側のhtml部分

<IntersectionObserver element-id="title1" @on-intersection-element="onIntersectionElement" />
          <div class="titleBlock">
            <h2 class="title" :class="{'-animate': isHeading1Active}">
              <span v-for="(char, i) in contents.c02_ttl.split('')" :key="i" :style="{ animationDelay: getDelay(i) }">
                {{ char }}
              </span>
            </h2>

使う側のデータとメソッド

data() {
    return {
      isHeading1Active: false,
      isHeading2Active: false,
    }
  },

  methods: {
    onIntersectionElement(value) {
      this.isHeading1Active = value;
    },
    onIntersectionElement2(value) {
      this.isHeading2Active = value;
    },

参考

https://codesandbox.io/s/vue-intersection-observer-rywdj?file=/src/App.vue:1332-1361