G
G
Gumper2020-10-29 17:58:04
Vue.js
Gumper, 2020-10-29 17:58:04

What is the correct way to use ResizeObserver?

Hello, I ran into a problem of violating one of the principles of good code such as DRY:

For example, I have a layout in which I use an observer:

<template>
  <div>
    <SidebarMobile v-if="!isDesktop" />
    <Header />
    <section id="content">
      <Sidebar v-if="isDesktop" />
      <Nuxt />
    </section>
    <Footer />
  </div>
</template>

<script>
  // Lib
 import { ResizeObserver } from "@juggle/resize-observer";
  // Components
  import Header from "@/components/Header.vue";
  import Sidebar from "@/components/Sidebar/Sidebar.vue";
  import SidebarMobile from "@/components/Sidebar/SidebarMobile.vue";
  import Footer from "@/components/Footer/Footer.vue";

  export default {
    components: {
      Header,
      Sidebar,
      SidebarMobile,
      Footer,
    },
    data() {
      return {
        width: 0,
      };
    },
    computed: {
      isDesktop() {
        return this.width > 768;
      },
    },
    mounted() {
      const ro = new ResizeObserver((entries, observer) => {
        for (const entri of entries) {
          this.width = entri.contentRect.width;
        }
      });
      ro.observe(document.body);
    },
  };
</script>


But now I need to do the same thing in another component:
<template>
  <div>
    <div v-if="!isDesktop"></div>
     <div v-if="isDesktop"></div>
  </div>
</template>

<script>
  // Lib
  import { ResizeObserver } from "@juggle/resize-observer";

  export default {
    data() {
      return {
        width: 0,
      };
    },
    computed: {
      isDesktop() {
        return this.width > 768;
      },
    },
    mounted() {
       const ro = new ResizeObserver((entries, observer) => {
        for (const entri of entries) {
          this.width = entri.contentRect.width;
        }
      });
      ro.observe(document.body);
    },
  };
</script>

And the question is how to avoid it, and am I using it correctly?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question