I built a single-page app in Nuxt.js 2 and Vue2. This has a very heavy WebGL visualizer that displays a 3D scene in two separate pages: SectionDesign
and SectionConfirm
<template>
<SectionDesign v-if="currentPage === 1"></SectionDesign>
<SectionPurchase v-if="currentPage === 2"></SectionPurchase>
<SectionConfirm v-if="currentPage === 3"></SectionConfirm>
</template>
My problem is that when I navigate from page 1 to page 2, my <canvas>
gets destroyed, I lose WebGL context, and all the loaded assets disappear. I have to re-initialize everything when I enter page 3. This is very resource-intensive and unoptimized. I'd like to create my <canvas>
only once, then "move it" from one section to the next.
I can do this with vanilla Javascript by appending a child to a new parent.
const canvas = document.getElementByID("myCanvas");
page1.appendChild(canvas);
function enterPage3() {
page3.appendChild(canvas);
}
This re-uses the same instance of the canvas, it just moves it to a new parent. Is there a way to achieve this with Vue2 and Nuxt.js?
CodePudding user response:
If you are not using layouts, create one as default.vue into /layouts dir.
Then use your WebGL viewer in the layout:
<template>
<div>
<!-- YourViewer component keeps visible in all pages using this layout -->
<YourViewer />
<!-- Every page is loaded inside nuxt tag -->
<nuxt />
</div>
</template>
CodePudding user response:
Nuxt has build in components like KeepAlive
that does not destroy your component / element
caches the inactive component instances without destroying them
Just wrap it
<KeepAlive>
<component />
</KeepAlive>