Vue: keep-alive with reusable components

Created on 27 Apr 2016  ·  2Comments  ·  Source: vuejs/vue

DEMO:
https://jsfiddle.net/banricho/7nhh8rho/

我们可以使用 Vue.extend() 创建一个 Vue 组件构造器。当在其它组件内部注册组件时,就等于新建了一个组件实例。组件构造器中的 data 使用一个函数返回,使得实例拥有自己独立的 data 对象。

以上描述在其它情况下都正常(如:局部注册的自定义标签),包括没有添加 keep-alive<component> 动态组件。但是,当动态组件添加了 keep-alive,会导致所有实例共享一个 data 对象。详情见 DEMO: https://jsfiddle.net/banricho/7nhh8rho/

不知道是不是我的姿势不正确…我也尝试了以下的方式:

const Demo = Vue.extend({
  // ...
});

const A = new Demo({});

这样的话,等于手动创建实例,并且需要指定 el 去挂载,无法让他们挂在同一个元素上动态切换。

目前有一种解决方案,就是使用一个函数,返回 Vue.extend() 组件构造器。然后再运行它,将返回值赋值给变量。但这相当于是创建了 N 个内容相同的组件构造器,而不是实例,应该不是优雅的方式。

感谢阅读我这么长的废话 -_-

Most helpful comment

Hello Chinese speaking users! Please make sure you add couple of Chinese characters in title of an issue, if whole description is in Chinese :smile: That way non-chinese can unsubscribe from issue right from notification page. Or better try to describe your issue in English too. xiexie!

All 2 comments

Hello Chinese speaking users! Please make sure you add couple of Chinese characters in title of an issue, if whole description is in Chinese :smile: That way non-chinese can unsubscribe from issue right from notification page. Or better try to describe your issue in English too. xiexie!

目前的 keep-alive 实现是通过判断 constructor 是否一样来做的,所以你切换的时候其实什么都没发生,ready 钩子也不会重新触发。事实上如果你想要重新触发生命周期钩子那就不应该用 keep-alive.

1.x 这个行为不会再做改动了,2.x 会重新设计 keep-alive 这个功能。

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aviggngyv picture aviggngyv  ·  3Comments

loki0609 picture loki0609  ·  3Comments

loki0609 picture loki0609  ·  3Comments

hiendv picture hiendv  ·  3Comments

seemsindie picture seemsindie  ·  3Comments