How to use keep-alive in vuejs?

2019-04-24 22:43发布

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>

users and data are route names. Is this correct way to do it. Are there any disadvantages of keep-alive?

标签: vue.js
1条回答
再贱就再见
2楼-- · 2019-04-24 23:18

The only disadvantage is that these components are kept in memory and therefore their state is saved and not reset.

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

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.

查看更多
登录 后发表回答