先说结论:<keep-alive>包裹的路由组件,该组件有两个特有的生命周期函数:activateddeactivated。其中,activated在路由组件被激活时触发;deactivated在路由组件失活时触发。

看具体的例子。项目目录如下。
在这里插入图片描述

  • 一般组件components/Banner.vue
<template>
    <div class="col-xs-offset-2 col-xs-8">
        <div class="page-header">
            <h2>Vue Router Demo</h2>
        </div>
    </div>
</template>

<script>
export default {
    name:"Banner"
}
</script>

<style>

</style>
  • 路由组件pages/Home.vue
<template>
  <div>
    <h2>Home组件内容</h2>
    <div :style="{opacity}">欢迎来到我们的网站!</div>
  </div>
</template>

<script>
export default {
    name:'Home',
    data(){
      return {
        opacity:1
      }
    },
    activated(){
      console.log("Home组件被激活了");
      this.timer = setInterval(() => {
        this.opacity -= 0.01;
        if(this.opacity < 0){
          this.opacity = 1;
        }
      },16)
    },
    deactivated(){
      console.log("Home组件失活了");
      clearInterval(this.timer);
    }
}
</script>

<style>

</style>

在这里插入图片描述

  • 路由组件pages/About.vue
<template>
  <h2>我是About的内容</h2>
</template>

<script>
export default {
    name:'About'
}
</script>

<style>

</style>
  • 路由器router/index.js
import VueRouter from "vue-router";
import Home from "../pages/Home";
import About from "../pages/About";

export default new VueRouter({
    routes:[
        {
            path:"/about",
            component:About
        },
        {
            path:"/home",
            component:Home
        }
    ]
})
  • App.vue
<template>
  <div>
    <div class="row">
      <Banner/>
    </div>
    <div class="row">
      <div class="col-xs-2 col-xs-offset-2">
        <div class="list-group">
          <router-link to="/about" active-class="active" class="list-group-item">About</router-link>
          <router-link to="/home" active-class="active" class="list-group-item">Home</router-link>
        </div>
      </div>
      <div class="col-xs-6">
        <div class="panel">
          <div class="panel-body">
            <keep-alive>
              <router-view></router-view>
            </keep-alive>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Banner from "./components/Banner.vue";

export default {
  name: 'App',
  components:{
    Banner
  }
}
</script>

在这里插入图片描述

  • 入口文件main.js
import Vue from 'vue'
import App from './App.vue'
import VueRouter from "vue-router";

import router from "./router/index";

Vue.config.productionTip = false;

Vue.use(VueRouter);

new Vue({
  render: h => h(App),
  router:router
}).$mount('#app')
  • 重启应用,测试效果。
    在这里插入图片描述
Logo

前往低代码交流专区

更多推荐