keep-alive vue的路由缓存 vue-router

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34664239/article/details/89499120

在vue项目中,尤其是h5制作的app,来回跳转的时候,有的地方需要做缓存,一来防止页面重复加载同样的数据造成服务器压力,二来防止页面重新加载造成卡顿,影响客户体验,今天,小闫就工作问题来帮助大家理解vue-router的缓存 - keep-alive

1. <router-view>
  • <router-view> 组件用于渲染路径匹配到的视图组件。 渲染的组件还可以内嵌自己的 ,根据嵌套路径,渲染嵌套组件。
  • <router-view> 组件有一个name属性,默认为default,渲染对应的路由配置中 components 下的相应组件。
//视图容器
<router-view class="view one"></router-view>
<router-view class="view two" name="a"></router-view>
<router-view class="view three" name="b"></router-view>

//路由配置
{
 path: '/main',
 components: Foo
},{
 path: '/',
 components: {
   default: Foo,
   a: Bar,
   b: Baz
 }
}
  • 因为它也是个组件,所以可以配合 和 使用。如果两个结合一起用,要确保在内层使用 <keep-alive>
<transition>
  <keep-alive>
    <router-view></router-view>
  </keep-alive>
</transition>
2.路由的router和route

vue-router中经常会操作的两个对象route和router
route

$route对象

$route对象指的是当前路由对象,包含了当前 URL 解析得到的信息。包含当前的路径,参数,query对象等。

**1.$route.path**
      字符串,对应当前路由的路径,总是解析为绝对路径,如 "/foo/bar"**2.$route.params**
      一个 key/value 对象,包含了 动态片段 和 全匹配片段,
      如果没有路由参数,就是一个空对象。
**3.$route.query**
      一个 key/value 对象,表示 URL 查询参数。
      例如,对于路径 /foo?user=1,则有 $route.query.user == 1,
      如果没有查询参数,则是个空对象。
**4.$route.hash**
      当前路由的 hash 值 (不带 #) ,如果没有 hash 值,则为空字符串。锚点
**5.$route.fullPath**
      完成解析后的 URL,包含查询参数和 hash 的完整路径。
**6.$route.matched**
      数组,包含当前匹配的路径中所包含的所有片段所对应的配置参数对象。
**7.$route.name    当前路径名字**
**8.$route.meta  路由元信息

$route对象

$router对象是全局路由的实例,是router构造方法的实例。主要是实现路由跳转使用。

//常用方法
this.$router.push('home');
this.$router.go(-1);
this.$router.replace('/')
......
3. keep-alive 实例

首先,在根vue文件中添加视图入口,在这里注意 和 的位置,以及判断当前路由是否设置了要做缓存

//app.vue
<transition :name="transitionName">
 <keep-alive>
  <router-view v-if="$route.meta.isKeepAlive"  class="router-view"></router-view>
 </keep-alive>
</transition>

<transition :name="transitionName">
 <router-view v-if="!$route.meta.isKeepAlive" class="router-view"></router-view>
</transition>

在route的meta属性中加一个属性isKeepAlive

// router/index.js
export default new VueRouter({
 saveScrollPosition: true,
 routes: [
     {path: '/', redirect: '/main'},
     {
         path: '/main', 
         name: 'MainIndex', 
         component: MainIndex,
         meta:{
             isKeepAlive: true
         }
     },
 ]
})

在有缓存的组件中处理路由

//MainIndex.vue
beforeRouteEnter(to,from ,next){
	//在这里访问不到this
  next(vm => {
      // 通过 `vm` 访问组件实例
      vm.cerateInterval();
  })
},
beforeRouteLeave(to,from ,next){
  clearInterval(this.timer);
  clearInterval(this.secondTimer);
  next();
}

猜你喜欢

转载自blog.csdn.net/qq_34664239/article/details/89499120