keep-alive

88 阅读1分钟
<!-- 组件中的数据会被重置 -->
<!-- 多次进入组件时   不触发销毁和渲染钩子函数 -->
<!-- keep-alive  解决组件重复执行销毁和创建的问题  从而提高渲染效率  解决缓存问题 -->
<!-- keep-alive  include:声明需要进入缓存的组件  exclude:声明不需要进入缓存的组件 -->
<!-- keep-alive  钩子函数  activated  deactivated -->


<div id="app">
        <button @click="compname='bcomp'">张三</button>
        <button @click="compname='acomp'">马仔</button>
        <button @click="compname='ccomp'">李四</button>
        <keep-alive include="acomp,bcomp">
            <component :is='compname'></component>
        </keep-alive>
  </div>
  activated() {
                    // 相当于替代created 和mounted
                    // 手动初始化   初始化需要修改的值
                    console.log(this.$data,"ccomp-activated");
                    // this.age = 0
                },
                deactivated() {
                    // 相当于替换destoryed
                    // 手动修改需要修改的值
                    console.log(this.$data,"ccomp-deactivated");
                    this.age = "50"
                },
components: {
          acomp: {
            template: `
             <div>{{name}}--{{age}}<button @click="age++">点击长一岁</button></div>
             `,
            data() {
              return {
                name: "马仔",
                age: 1,
              };
            },
          },
          bcomp: {
            template: `
            <div>
                {{name}} --{{age}}<button @click="age--">点击小一岁</button>
                </div>
            `,
            data(){
                return{
                    name:"张三",
                    age:2
                }
            }
          },
          ccomp:{
            template:`
            <div>{{name}}--{{age}}<button @click="age++">点击长一岁</button></div>
            `,
            data(){
                return{
                    name:"李四",
                    age:3
                }
            }
          }
        },