使用<keep-alive>缓存嵌套组件及其内容的一种方法

665 阅读1分钟

关键字: <keep-alive>, VueRouter

有时在切换页面后, 需要缓存当前展示的嵌套组件及其内容. 即: 用户输入数据后, 切换到其他页面再切回原来页面时, 不仅自动展开之前所示的组件, 同时数据也能缓存下来.

<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。

style

<style>
  .edit {
    text-align: center;
  }
</style>

html

<div id="app">
  <button @click="$router.push('/home')">首页</button>
  <button @click="$router.push('/edit')">编辑</button>
  <hr />
  <!-- 这里的keep-alvie用于缓存外层的Home和Edit组件, 在这两个组件之间时input框里的内容不会消失 -->
  <keep-alive>
    <router-view></router-view>
  </keep-alive>
</div>

js

<script>
  // 用于记录“编辑”页面选中的是哪个组件
  let choice = "basic";
  const Home = {
    template: `
    <div>我是首页 <input type="text"> </div>
    `,
  };
  const Edit = {
    template: `
    <div class="edit">
      <button @click="$router.push('/binfo')" ref="basic">基本信息</button>
      <button @click="$router.push('/einfo')" ref="education">学历信息</button>
      <hr />
      <!-- 这里的keep-alvie用于缓存内层的BInfo和EInfo组件, 在这两个组件之间时input框里的内容不会消失 -->
      <keep-alive>
        <router-view></router-view>
      </keep-alive>
    </div>
    `,
    // 切换到Edit页面时,根据choice触发点击事件
    activated() {
      console.log("okkkkkkk");
      console.log(this.$refs);
      this.$refs[choice].click();
    },
  };
  const BInfo = {
    template: `
    <div>
      姓名:<input type='text'> <br />
      年龄:<input type='text'> <br />
      性别:<input type='text'>
    </div>
    `,
    // 路由进入时,将choice记录下来
    beforeRouteEnter(to, from, next) {
      choice = "basic";
      next();
    },
  };
  const EInfo = {
    template: `
    <div>
      院校:<input type='text'> <br />
      学历:<input type='text'>
    </div>
    `,
    // 路由进入时,将choice记录下来
    beforeRouteEnter(to, from, next) {
      choice = "education";
      next();
    },
  };
  const routes = [
    { path: "/home", component: Home },
    {
      path: "/edit",
      component: Edit,
      children: [
        { path: "/binfo", component: BInfo },
        { path: "/einfo", component: EInfo },
      ],
    },
  ];
  const router = new VueRouter({
    routes,
  });
  const vm = new Vue({
    el: "#app",
    router,
  });
</script>

结果

动画6.gif