keep-alive

keep-alive的生命周期

1.deactived当组件被缓存时,会自动触发组件的deactived生命周期函数。

2.actived当组件被激活时,会自动触发组件的actived生命周期函数。

当组件第一次被创建的时候,既会执行created创建也会activated被激活

当切换组件时包裹了<keep-alive></keep-alive>的组件会被缓存。

3.include 选择需要缓存的组件

多组件需要英文逗号

include="Left,Right"

4.exclude 选择缓存时需要排除的标签

exclude="Right"

1.App.vue

<template>
  <div id="app">
    <button @click="conName = 'Left'">展示left</button>
    <button @click="conName = 'Right'">展示right</button>
    <div class="box">
       <keep-alive exclude="Right">
      <!-- <keep-alive include="Left"> -->
        <component :is="conName"></component>
      </keep-alive>
    </div>
  </div>
</template>
<script>
import Left from "./components/Left.vue";
import Right from "./components/Right.vue";
export default {
  data() {
    return {
      conName: "Left",
    };
  },
  activated() {},
  watch: {},
​
​
  mounted() {},
  methods: {},
  components: {
    Left,
    Right,
  },
};
</script>
<style>
</style>
​

2.Left.vue

<template>
  <div>
    <div class="Left">
      <button @click="add">+1</button>
      <h3>{{ count }}</h3>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      count: 0,
    };
  },
  activated() {},
  watch: {},
  created() {
    console.log("组件被创建了");
  },
  destroyed() {
    console.log("组件被销毁了");
  },
  activated() {
    console.log("组件被激活了");
  },
  deactivated() {
    console.log("组件被缓存了");
  },
  mounted() {},
  methods: {
    add() {
      this.count++;
    },
  },
};
</script>
<style scoped>
.Left {
  width: 100%;
  height: 200px;
  background: yellowgreen;
}
</style>
​

3.Right.vue

<template>
    <div>
  <div class="Right"></div>
    </div>
</template>
<script>
export default {
   data() {
      return {
      }
   },
   activated() {
   },
 watch: {
},
created(){
},
mounted(){
},
methods:{
}
}
</script>
<style scoped>
.Right{
    width: 100%;
    height: 200px;
    background:blue;
}
</style>
​
posted @ 2021-09-10 15:38  ajaXJson  阅读(142)  评论(0编辑  收藏  举报