猫码让前端飞Web前端之路

vue中动态化的按需使用keep-alive

2020-04-04  本文已影响0人  ComfyUI

主要讲下啥是 keep-alive、具体到项目中怎么用的问题。
项目相关:panda-mall

1、啥是 keep-alive?

2、meta 路由元信息

(1)介绍

(2)实现

  // 首页
  {
    path: '*',
    name: 'Home',
    // 路由懒加载:https://router.vuejs.org/zh/guide/advanced/lazy-loading.html
    // webpackPreload:https://www.jianshu.com/p/bbdcfeee7fbc
    component: () => import(/* webpackPreload: true */ '@/views/home'),
    meta: {
      keepAlive: true,
      deepth: 1
    }
  },
  // 商品列表
  {
    path: '/product',
    name: 'Product',
    component: () => import('@/views/product'),
    meta: {
      keepAlive: true,
      deepth: 2
    }
  },
  // 商品详情
  {
    path: '/detail',
    name: 'Detail',
    component: () => import('@/views/detail'),
    meta: {
      keepAlive: true,
      deepth: 3
    }
  },
<template>
  <div id="app">
    <keep-alive :include="include">
      <router-view v-if="$route.meta.keepAlive" />
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive" />
  </div>
</template>
export default {
  data() {
    return {
      include: []
    };
  },
  watch: {
    $route(to, from) {
      // 如果要to(进入)的页面是需要keepAlive缓存的,把name push进include数组中
      if (to.meta.keepAlive) {
        !this.include.includes(to.name) && this.include.push(to.name);
      }
      // 如果 要 form(离开) 的页面是 keepAlive缓存的,
      // 再根据 deepth 来判断是前进还是后退
      // 如果是后退:
      if (from.meta.keepAlive && to.meta.deepth < from.meta.deepth) {
        const index = this.include.indexOf(from.name);
        index !== -1 && this.include.splice(index, 1);
      }
    }
  }
};
 // router.js
{
    path: '*',
    name: 'Home', // name要大小写要一致
    component: () => import(/ '@/views/home'),
    meta: {
      keepAlive: true,
      deepth: 1
    }
}

// home.vue
export default {
    name: 'Home', // name要大小写要一致
}

3、hack 手法

(1)问题

(2)实现

  // 首页
  {
    path: '*',
    name: 'Home',
    component: () => import('@/views/home'),
    meta: {
      keepAlive: true
    }
  },
  // 商品列表
  {
    path: '/product',
    name: 'Product',
    component: () => import('@/views/product'),
    meta: {
      keepAlive: true
    }
  },
  // 商品详情
  {
    path: '/detail',
    name: 'Detail',
    component: () => import('@/views/detail'),
    meta: {
      keepAlive: true
    }
  },
<template>
  <div id="app">
    <keep-alive>
      <router-view v-if="$route.meta.keepAlive" :key="key" />
    </keep-alive>
    <router-view v-if="!$route.meta.keepAlive" :key="key" />
  </div>
</template>

<script>
  export default {
    computed: {
      key() {
        return this.$route.fullPath;
      }
    }
  };
</script>
  onClick() {
      this.$router.push({
        path: '/product',
        query: {
          t: +new Date()
        }
      })
  }

3、小结

上一篇下一篇

猜你喜欢

热点阅读