Ask a question
Recently, I found a problem when working on a project. After using the keep-alive tag, I entered a route for a series of operations, then clicked on the browser to back up, and entered the route just now. The data that was operated on the page was not initialized!
Analyze the problem
This is because keep-alive caches the route page, so the route does not complete the entire lifecycle, does not destroy, so reentry does not trigger other lifecycle hooks, such as created, etc.
Solve the problem
(1). View official documents
When the component is switched within keep-alive, its two life cycle hook functions, activated and deactivated, will be executed accordingly.
include - String or regular expression. Only matching components will be cached.
exclude - String or regular expression. No matching components are cached.
<!-- Comma-separated strings --> <keep-alive include="a,b"> <component :is="view"></component> </keep-alive> <!-- Regular expressions (use `v-bind`) --> <keep-alive :include="/a|b/"> <component :is="view"></component> </keep-alive> <!-- Array (use `v-bind`) --> <keep-alive :include="['a', 'b']"> <component :is="view"></component> </keep-alive>
Match first checks the component's own name option, and if the name option is not available, it matches its local registration name (key value of the parent component components option). Anonymous components cannot be matched.
(2). Listen to routing changes
Use watch to listen for route changes, but I found that the listener route only takes effect when the component is wrapped by keep-alive, and does not take effect when it is not wrapped. The reason is unknown. If you understand, please leave a message to tell me!
watch: { '$route' (to, from) { // Respond to routing changes... } }
I found that the hook beforeRouteUpdate is not available yet, I don't know where something went wrong.
beforeRouteUpdate (to, from, next) { // react to route changes... // don't forget to call next() }
The above method of vue to prevent a component from being cached by keep-alive is all the content I share with you. I hope you can give you a reference and I hope you can support me more.