玩vue也有一段时间了,vue确实相对于react和angular要好入门一点,但是vue的坑也是特别的多,特别是对于新手来说,那么我今天就来说下vue中的keep-alive这个组件,之所以要说这个组件,原因是我在做项目的时候运到过这个问题,因此来聊下他,keep-alive这个组件的作用其实就是可以保存页面的缓存,不用我们再来到这个页面的时候再去请求服务器来渲染我们整个页面,从而可以减少页面像服务器请求的次数,用来缓存组件,避免多次加载相应的组件,减少性能消耗
全部组件缓存
1 2 3 4 5 6 7 8 9
| //这个是所有组件缓存 <keep-alive> <component></component> //注意这个是vue中的,不是我们自已定义的 </keep-alive> //这个是全部路由的缓存 <keep-alive> <router-view></router-view> </keep-alive>
|
缓存部分页面或者组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| //这个是组件的代码 <keep-alive> <router-view v-if="$route.meta.keepAlive" ></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"></router-view> //这个是路由配置的代码 前面部分省略... routes: [ { path: '/home', name: 'content', component:Content, meta: { keepAlive:false } //注意如果这里为false,Content组件不缓存 }, { path:'/follow', name:'follow', component:Follow }, { path:'/column', name:'column', component:Column }, { path:'/userinfo', name:'user', component:Userinfo }, { name:'articel', path: '/article/:id', component: Article }, /* {path:'*', redirect:'/home'},*/ { path: '/', redirect: '/home' } ] ......
|
使用新增属性inlcude/exclude
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| //注意这个方法只能在vue2.1.0之后使用 <!-- 逗号分隔字符串 --> <keep-alive include="a,b"> <component :is="view"></component> //is表示的是绑定了一个动态的变量,这个变量可以来源于data里面的属性 </keep-alive> <!-- 正则表达式 (使用 `v-bind`) --> <keep-alive :include="/a|b/"> <component :is="view"></component> </keep-alive> <!-- 数组 (使用 `v-bind`) --> <keep-alive :include="['a', 'b']"> <component :is="view"></component> </keep-alive> //其中a,b是组件的name
|
如果有的小伙伴也更我运到了同样的问题,那么希望这篇文章对你们有点帮助