【Vue】Re18 Router 第五部分(KeepAlive)

一、KeepAlive概述

默认状态下,用户点击新的路由时,是访问新的组件

那么当前组件是会被销毁的,然后创建新的组件对象出来

如果某些组件频繁的使用,将造成内存空间浪费,也吃内存性能

所以需求是希望组件能被缓存起来,不是立即销毁

生命周期的创建函数 create(); 和销毁函数 destory(); 都将反复调用

二、使用

只需要把router-view做为keep-alive的子元素就行了

<template>
  <div id="app">
    <router-link to="/home" tag="button" >去首页</router-link>
    <router-link to="/about" tag="button" >去关于</router-link>
    <router-link :to="/user/+username" tag="button" >用户管理</router-link>
    <router-link :to="ppp" tag="button" >profile</router-link>
<!--    <button @click="toProfile" >profile</button>-->
<!--    <button @click="toHome">首页</button>-->
<!--    <button @click="toAbout">关于</button>-->
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
    <p>
      <button @click="getRouterInstance">获取Router对象</button>
      <button @click="getCurrentRouteInstance">获取Route对象</button>
    </p>
  </div>
</template>

如果组件的周期不再销毁,那么生命状态则发生了改变

在访问时是被激活的状态

如果离开了组件时,则是非激活状态

对应了两个生命周期函数:

activated () {
  // todo ...  
}
deactivated () {
  // todo ...  
}

注意!!!上述的函数仅对keep-alive处理的组件有效

三、关于重定向路由BUG问题

 /router/index.js 

父级路由

  /* 重定向首页路由配置 */
  {
    path : '', /* 缺省值默认指向 '/' */
    redirect : '/home',
  },

子级路由

    children : [ /* 设置子路由 */
      {
        path : '', /* 这个缺省默认/home */
        redirect : 'news',
      },

重定向home的时候触发子路由的重定向

向下继续重定向到/home/news

解决方案:

移除子路由的重定向,在组件初始化时重定向一次,后续不再重定向

还有要记录用户之前访问的组件的路由,回到之前的父组件时访问的子组件

<template>
  <div>
    <h3>这是首页Home组件</h3>
    <p>
      首页Home组件的内容 <br>
      <router-link to="/home/news">新闻列表</router-link>
      <router-link to="/home/messages">消息列表</router-link>
    </p>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: "Home",
  created() {

  },
  data () {
    return {
      path : '/home/news'
    }
  },
  activated() {
    this.$router.push(this.path);
  },
  // deactivated() {
  //   this.path = this.$route.path;
  // }
  beforeRouteLeave (to, from, next) {
    this.path = this.$route.path;
    next();
  }
}
</script>

<style scoped>

</style>

四、Keep-Alive的两个属性

    <keep-alive
      include="Home,Message"
      exclude="News,Profile"
    >
      <router-view></router-view>
    </keep-alive>

include表示需要缓存在里面的组件

exclude表示排除,不要缓存的组件

默认是使用正则表达式,符合正则规则的组件名称,就会把该组件选中

也可以是直接写组件的名称表示,注意不要有空格

组件的名称就是这个:

用途主要是为了排除特定不需要缓存的组件,一般需要缓存的不需要填写属性表示了

 

posted @ 2020-11-03 09:57  emdzz  阅读(103)  评论(0编辑  收藏  举报