美文网首页
keep-alive

keep-alive

作者: 迷失的信徒 | 来源:发表于2022-04-16 19:52 被阅读0次

1、keep-alive的使用

在SPA应用中,我们有时候需要来回的切换路由,而组件就会重复的创建和销毁。
keep-alive是Vue内置的一个组件,它可以使被包含的组件保留状态,可以避免重复渲染。
相对应的router-view也是一个组件,如果外面想所有路径匹配到的视图组件都能被缓存起来,可以将它用keep-alive包裹起来。

app.vue
<template>
  <div id="app">
    <router-link to="/home">首页</router-link>
    <router-link to="/about">关于</router-link>
    <router-link :to="'/user/' + userId">用户</router-link>
    <router-link :to="{path:'/profile',query:{name:'why',age:18,height:180}}">档案</router-link>
   <keep-alive>
      <router-view></router-view>
    </keep-alive>
  </div>
</template>
home.vue
<template>
  <div>
    <h2>我是home组件</h2>
    <router-link to="/home/news">新闻</router-link>
    <router-link to="/home/message">消息</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
  export default{
    created() {
      console.log('home created');
    },
    destroyed() {
      console.log('home destroyed');
    }
  }
</script>
<style>
</style>

如上图所示,我们在app.vue中用keep-alive把这四个组件都缓存起来,这里我们只在home.vue中检验他的创建和销毁,运行、切换home created,只输出了一次,home destroyed没有输出;则表示组件只被创建了一次,且被缓存起来并没有被销毁。

但如果说向home.vue中也有两个子组件展示的时候,切换路由,返回的时候还是要展示上次离开时的组件;则home.vuescript位置应该改成如下:

<script>
  export default{
    data() {
      return {
        path: '/home/news'//初始显示组件路由
      }
    },
    created() {
      console.log('home created');
    },
    destroyed() {
      console.log('home destroyed');
    },
    activated() {
      console.log('activated',this.path);
      this.$router.push(this.path)
    },
    // deactivated() {
    //   this.path = this.$route.path
    //   console.log('deactivated',this.path);
    // },
    beforeRouteLeave(to,from,next) {
      this.path = this.$route.path
      console.log('beforeRouteLeave',this.path);
      next()
    }
  }
</script>

activated()activated()方法只有在keep-alive组件中才有效果,不然是无效的。
我们这里的原理是:

  • 1、设置一个变量path来保存离开时的路由。
  • 2、当组件状态变为活跃后跳转为离开时路由。

至于为什么不在上面的deactivated()中通过this.path = this.$route.path获取路由,那是因为该方法执行的时机this.$route.path已经不是我们所想要保存的路由,而是跳转之后显示出来组件的路由,所以我们这里通过beforeRouteLeave()方法来获取离开组件时路由。

2、Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/xxx/xxx"

这里我们还会碰到一个小问题,当我们从其他组件切换会home.vue组件时会执行push方法,而当组件变为活跃状态时还会调用一次push方法,当两次push地址相同时,则会报Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/home/news".
解决方法:

  • 1、在router配置文件(/router/index.js)下添加
const VueRouterPush = Router.prototype.push
Router.prototype.push = function push (to){
  return VueRouterPush.call(this,to).catch(err => err)
}
  • 2、使用 catch 方法捕获异常
this.$router.push(route).catch(err => {
  console.log('跳转异常:',err)
})
  • 3、在进行路由跳转时添加判断,若一致则不跳转
go(item) {
  if (this.$route.path !== item.url) {
    this.$router.push({ path: item.url })
  }
}

3、keep-alive的exclude属性

exclude:字符串或正则表达式,任何匹配的组件都不会被缓存
这里以profile.vue组件验证为例

<template>
  <div>
    <h2>我是profile组件</h2>
    <p>{{$route.query.name}}</p>
    <p>{{$route.query}}</p>
  </div>
</template>
<script>
  export default{
    name:'profile',
    created() {
      console.log('profile created');
    },
    destroyed() {
      console.log('profile destroyed');
    },
  }
</script>
<style>
</style>

注:这里要设置script中的name属性,以便于keep-alive组件识别匹配组件。
而在keep-alive使用以下设置

<keep-alive exclude="profile">
      <router-view></router-view>
    </keep-alive>

这样就做到了profile.vue组件的随时创建和随时销毁

相关文章

网友评论

      本文标题:keep-alive

      本文链接:https://www.haomeiwen.com/subject/inbasrtx.html