This time I will bring you how to use vue's specified component cache. What are theprecautions for using vue's specified component cache?. The following is a practical case, let's take a look.
keep-alive Introduction
keep-alive is a built-in component of Vue that allows included components to retain their state or avoid re- render.
Usage is also very simple:
props
##include-Stringor regular expression , only matching components will be cachedexclude - string or
regular expression, any matching components will not be cached
// 组件 a export default { name: 'a', data () { return {} } }可以保留它的状态或避免重新渲染 可以保留它的状态或避免重新渲染
meet vue-router
router-view is also a component. If it is directly wrapped in keep-alive, allviewcomponents matching the path will be cached:
Question
What should I do if I only want a certain component in the router-view to be cached? ? Use include/excludeAdd the router.meta attribute
Use include/exclude
// 组件 a export default { name: 'a', data () { return {} } }
// routes 配置 export default [ { path: '/', name: 'home', component: Home, meta: { keepAlive: true // 需要被缓存 } }, { path: '/:id', name: 'edit', component: Edit, meta: { keepAlive: false // 不需要被缓存 } } ]
B jumps to A, A does not refresh
C jumps to A, A refreshes
Implementation method
{ path: '/', name: 'A', component: A, meta: { keepAlive: true // 需要被缓存 } }
export default { data() { return {}; }, methods: {}, beforeRouteLeave(to, from, next) { // 设置下一个路由的 meta to.meta.keepAlive = true; // 让 A 缓存,即不刷新 next(); } };
export default { data() { return {}; }, methods: {}, beforeRouteLeave(to, from, next) { // 设置下一个路由的 meta to.meta.keepAlive = false; // 让 A 不缓存,即刷新 next(); } };
Summary
The routing method is good, you don’t need to care about which page jumps to, just router.go(-1) can go back , no additional parameters are required. However, in non-single-page applications, keep-alive cannot be cached effectively = = I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to php Chinese Other related articles online! Recommended reading:How to call child components from Angular parent components
How to learn vue for beginners
The above is the detailed content of How to use specified component cache of vue. For more information, please follow other related articles on the PHP Chinese website!