Answer the question
In order to leave comments, you need to log in
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>
<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>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question