Creating multiple instances of a component without multiple imports

Viewed 310

So currently I'm importing a component multiple times with different names.

import Page1 from "./Page/Page"
import Page2 from "./Page/Page"
import Page3 from "./Page/Page"
import Page4 from "./Page/Page"

I'm doing this as I want each instance to have its own set of properties, which then I use <keep-alive> to maintain their state.

I am also using them inside a <component :is="".

I was wondering if there was a way to create multiple instances without multiple import.

Codesandbox:

https://codesandbox.io/s/5x391j8y4x

you will notice that if I switch between the HelloWorlds, that the input will maintain their instances (input will change to what they were holding)

1 Answers

You don't need to use <component> because you only have one component type that you want to use: HelloWorld. <component> is only needed when you want to dynamically render different component types.

The reason why you require <keep-alive> is because the HelloWorld component has local state (msg) which will be lost once the component instance is destroyed.

You will need to use key to force Vue to instantiate a new instance of HelloWorld based on the page, and you need <keep-alive> to prevent each instance from being destroyed when you switch between pages.

Here's an example:

<ul>
  <li
    v-for="page in pages"
    @click="currentPage = page" 
    :key="page.key">{{ page.title }}</li>
</ul>

<keep-alive>
  <hello-world
    :key="currentPage.key"
    :title="currentPage.title"/>
</keep-alive>
import HelloWorld from './components/HelloWorld'

export default {
  name: "App",
  
  components: {
    HelloWorld,
  },

  data() {
    const pages = [
        {
            key: "home",
            title: "Home"
        },
        {
            key: "about",
            title: "About"
        },
        {
            key: "contact",
            title: "Contact"
        }
    ]
    const currentPage = pages[0]

    return {
      currentPage,
      pages
    }
  }
}
Related