简体   繁体   English

无需多次导入即可创建组件的多个实例

[英]Creating multiple instances of a component without multiple imports

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.我这样做是因为我希望每个实例都有自己的一组属性,然后我使用<keep-alive>来维护它们的状态。

I am also using them inside a <component :is="" .我也在<component :is=""中使用它们。

I was wondering if there was a way to create multiple instances without multiple import.我想知道是否有一种方法可以创建多个实例而无需多次导入。

Codesandbox:代码沙盒:

https://codesandbox.io/s/5x391j8y4x 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)您会注意到,如果我在 HelloWorlds 之间切换,输入将保持它们的实例(输入将更改为它们所持有的)

You don't need to use <component> because you only have one component type that you want to use: HelloWorld .您不需要使用<component> ,因为您只有一种要使用的组件类型: HelloWorld <component> is only needed when you want to dynamically render different component types. <component>仅在您想要动态呈现不同的组件类型时才需要。

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.您需要<keep-alive>的原因是因为HelloWorld组件具有本地状态 ( msg ),一旦组件实例被销毁,该状态就会丢失。

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.您将需要使用key来强制 Vue 基于页面实例化一个新的HelloWorld实例,并且您需要<keep-alive>以防止在页面之间切换时每个实例都被破坏。

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
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM