【问题标题】:Keep list components alive in Vue在 Vue 中保持列表组件处于活动状态
【发布时间】:2017-02-09 08:14:03
【问题描述】:

我有一个使用v-for 渲染的组件列表。并非所有组件都同时显示。我使用slice 对渲染组件数组进行分页。

不应重新渲染这些组件,因为其中一些具有用户输入的数据,而另一些则执行与网络相关的任务。

我尝试使用<keep-alive>。但是,这只会渲染第一个组件。

<keep-alive>
    <component :is="component.type" :key="component.id" v-for="component in components">
</keep-alive>

如何保持组件的动态列表有效?

【问题讨论】:

  • 活着的意思是防止重新渲染?也许是因为失去对组件的观察?这样做很容易。让我知道它是否适合你
  • @MU 是的,我需要防止重新渲染。失去对组件的观察是什么意思?
  • 你到底是什么问题,是不是:this renders only the first component
  • @Saurabh 是的。即使components 数组中有多个项目,也只显示第一个。不过,它正确地保留了数据,因此不会重新渲染。

标签: vue.js vue-component


【解决方案1】:

我阅读了 Vue 的 &lt;keep-alive&gt; 的源代码,并创建了与列表配合得很好的新组件。

包名是vue-keep-alive-global。这是一个链接,https://www.npmjs.com/package/vue-keep-alive-global

使用方法:

<KeepAliveGlobal>
    <YourComponent
        :key="uniqueKey"
    />
</KeepAliveGlobal>

带数组,

<template v-for="(item, index) of array">
    <KeepAliveGlobal :key="`blah-blah-${index}`">
        <YourComponent
            :item="item"
            :key="`your-component-${index}`"
        />
    </KeepAliveGlobal>
</template>

KeepAliveGlobal 会按键缓存组件。

【讨论】:

    【解决方案2】:
     <div v-for="comp in compList"  :key="'container'+comp.keyId" >
        <keep-alive>
          <component :is="comp.type" :key="comp.keyId"></component>
        </keep-alive>
     </div>
    

    以上内容对我有用。将元素正确推送到 compList 会创建它们各自组件的新实例。在数组中移动元素的索引,维护key,不调用destroy/create,并维护每个组件内的状态

    【讨论】:

      【解决方案3】:

      Vue 文档中有关于您的用例的注释

      注意,&lt;keep-alive&gt; 是为它有一个直接的情况而设计的 正在切换的子组件。如果你有它不起作用 v-for 在里面。当有多个条件孩子时,如 上面,` 要求只有一个孩子在 时间。

      https://vuejs.org/v2/api/#keep-alive

      改用v-once 指令。

      https://vuejs.org/v2/api/#v-once

      【讨论】:

        【解决方案4】:

        在小提琴中测试了上面的答案并且不起作用。 https://jsfiddle.net/z11fe07p/680/

         <div v-for="component in myComponents"  :key="component.id" >
            <keep-alive>
              <component :is="component.type" 
                       :name="component.name">
              </component>
            </keep-alive>
         </div>
        

        另外我会避免使用 vue 保留字,例如 components,因为在 vue 实例中有一个 components 键,它告诉实例正在使用哪些组件。

        【讨论】:

        • 这是我之前尝试过的,但也注意到它也不起作用。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-14
        • 1970-01-01
        • 1970-01-01
        • 2014-06-18
        • 2012-01-03
        • 2014-11-16
        • 2012-05-24
        相关资源
        最近更新 更多