M -
M -

Reputation: 28482

How do I reuse the same instance of a component in Nuxt.js

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?

Upvotes: 1

Views: 1084

Answers (2)

Ilijanovic
Ilijanovic

Reputation: 14904

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>

Upvotes: 1

thebyteland
thebyteland

Reputation: 376

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>

Upvotes: 0

Related Questions