问题描述
基本上,我想在路由器视图中保持 2 个组件的活动状态并且它可以工作,但是,我不知道我是否做得正确.
Basically, I want to keep alive 2 components in router-view and it works, however, I don't know if I am doing it correctly.
<keep-alive include="users, data">
<router-view></router-view>
</keep-alive>
用户和数据是路由名称.这是正确的做法吗.keep-alive 有什么缺点吗?
users and data are route names. Is this correct way to do it. Are there any disadvantages of keep-alive?
推荐答案
唯一的缺点是这些组件保存在内存中,因此它们的状态被保存而不是重置.
The only disadvantage is that these components are kept in memory and therefore their state is saved and not reset.
你也失去了生命周期钩子,比如 created、mounted 等,因为组件不再从头开始重建.您可以使用特定于 keep-alive
组件的钩子替换这些生命周期钩子.例如:
You also lose lifecycle hooks like created, mounted, etc. since the component is not being rebuilt from scratch anymore. You can replace those lifecycle hooks with hooks that are specific to keep-alive
components. For example:
https://vuejs.org/v2/api/#activated
keep-alive
是劣势还是优势完全取决于您的情况.如果您想保持状态,因为您想在 keep-alive
组件之间快速且频繁地切换,这可能是一个优势.如果你真的通过构建和销毁组件来依赖一个干净的状态,这可能是一个劣势.
Whether keep-alive
is a disadvantage or advantage is entirely up to your scenario. If you want to keep the state because you want to switch fast and often between the keep-alive
components, it could be an advantage. If you really rely on a clean state through components being built and destroyed, it could be a disadvantage.
这篇关于如何在 vuejs 中使用 keep-alive?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!