keep-alive的原理及使用

内置组件keep-alive
主要用于保留组件状态或避免重新渲染。
keep-alive生命周期钩子函数:activated、deactivated,每次进入离开过程都调用一次

效果一:

comp1 页面跳转至 home页面, home页面不刷新
comp2 页面跳转至 home页面, home页面刷新

//配置路由 router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Comp1 from '@/pages/comp1'
import Comp2 from '@/pages/Comp2'

Vue.use(Router)
const router = new Router({
     
  routes: [
    {
     
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld,
      meta: {
     
        keepAlive: true    //先默认它需要缓存
      }
    },
    {
     
      path: '/comp1',
      name: 'Comp1',
      component: Comp1
    }, {
     
      path: '/comp2',
      name: 'Comp2',
      component: Comp2
    }
  ]
})
export default router

App.vue

<template>
  <div id="app">
	    <router-link to="/">home</router-link>
	    <router-link to="/comp1">comp1</router-link>
	    <router-link to="/comp2">comp2</router-link>
	    
		<keep-alive>
		  <router-view v-if="$route.meta.keepAlive">  <!-- 此处会展示被缓存组件 -->
		  </router-view>
		</keep-alive>
		<router-view v-if="!$route.meta.keepAlive"></router-view>   <!-- 此处重新渲染的组件 -->
  </div>
</template>
<script>
export default {
     
  name: 'App'
}
</script>

HelloWorld.vue

<template>
  <div>
	<button @click="fn">加加加</button>
	<p>{
     {
     num}}</p>
  </div>
</template>
<script>
export default {
     
  name: 'HelloWorld',
  data () {
     
    return {
     
      num: 0
    }
  },
  methods: {
     
    fn () {
     
      const count = this.num
      this.num = count + 1
    }
  },
 //keep-alive生命周期钩子函数:activated、deactivated
   activated () {
     
    console.log('进入缓存页面调用')
  },
  deactivated () {
     
    console.log('离开缓存页面调用')
  }
}
</script>

Comp1.vue

<template>
  <div class="hello">
  <p>comp1,comp1,comp1</p>
  </div>
</template>
<script>
export default {
     
  name: 'Comp1',
  beforeRouteLeave (to, from, next) {
     
 //  console.log('失活组件里beforeRouteLeave', 1)
    to.meta.keepAlive = true   //此页面跳转至home页面,home页面不刷新
    next()
  }
}
</script>

Comp2.vue

<template>
  <div>
	<p>comp2,comp2,comp2</p>
  </div>
</template>
<script>
export default {
     
  name: 'Comp2',
  beforeRouteLeave (to, from, next) {
     
    to.meta.keepAlive = false  //此页面跳转至home页面,home页面刷新
    next()
  }
}
</script>

你可能感兴趣的:(vue,vue.js,前端)