Use of keep-alive in Vue·

<keep-alive>usage of


Use background:

  • Some components do not require multiple init, but in vue, every time the corresponding page is clicked, a new data request and rendering of the page DOM component tree will be performed each time
  • When the user clicks a link to jump to the next page and wants to return to the previous page, the traces of the last operation are still there.

Instructions:

  • Use the keep-alive component in vue, component address: https://github.com/vuejs/vue/blob/dev/src/core/components/keep-alive.js

1. Add keepAlive to the page you want to cache in the router.js routing table.

 {
    
    
                    path: '/403',
                    //  路由实现页面懒加载
                    component: () => import('../components/page/403.vue'),
                    meta: {
    
    
                    //  设置‘保活’
                        keepalive: true,
                        title: '403' 
                    }
                },

Second, use tags to wrap the page references that need to be cached.

 <transition name="move" mode="out-in">
                    <keep-alive :include="tagsList">
                        <router-view></router-view>
                    </keep-alive>
                </transition>

Use of include and exclude attributes

  • First add a name to the component you want to handle specially:
export default{
    
    
   name:'home',// 这里的name是用来进行特殊处理的.
   data(){
    
    
   	return{
    
    }
   }
}
  • <keep-alive>Add in the parent component of the component exclude= ‘home’, so that the home component will not be retained, and will be re-rendered every time you enter it, leaving no traces.
<keep-alive exclude=‘home’> 
	<router-view></router-view> // 其实如果里面没有内容可以写成单标签
</keep-alive>
  • If there are multiple special treatments, just add excludethem later.
  • If there are only a few components that require special treatment, they can be used include.

3. The life cycle of components after using keep-alive


  • Components after using keep-alive will have two more life cycles of actived and deactived
  • 1. Actived: When the page component is loaded for the first time, it will be triggered, and the hook sequence of its triggering is created->mounted->activated
  • 2. Deactived: Triggered when the user leaves the component page.

Guess you like

Origin blog.csdn.net/weixin_40944062/article/details/105151778