【vue2第十八章】VueRouter 路由嵌套 与 keep-alive缓存组件(activated,deactivated)
VueRouter 路由嵌套
在使用vue开发中,可能会碰到使用多层级别的路由。比如:
其中就包含了两个主要页面,首页,详情,但是首页的下面又包含了列表,喜欢,收藏,我的四个子路由。
此时就需要配置子路由通过使用children
:
import Vue from 'vue'
import App from './App.vue'
import MyDetail from './views/MyDetail.vue'
import MyFriend from './views/MyFriend.vue'
import MyIndex from './views/MyIndex.vue'
import MyLike from './views/MyLike.vue'import VueRouter from 'vue-router'
Vue.use(VueRouter)Vue.config.productionTip = falseconst router = new VueRouter({routes: [//两个主要页面详情和首页{path: "/MyIndex", component: MyIndex, //添加children值数组,继续写组件和路径children: [{ path: "/friend", component: MyFriend },{ path: "/like", component: MyLike }]},{ path: "/MyDetail", component: MyDetail }]
});
new Vue({render: h => h(App),router
}).$mount('#app')
keep-alive缓存组件
问题就是在浏览页面的时候,已经将页面下滑了,然后点击到了某一个文章的详情页,最后返回到文章目录时又回到了最顶部,就比如我们刷抖音,我们往下刷,看到一个比较有意思的视频博主,点进去看主页,然后返回回来结果给我返回到了打开抖音的第一个视频。
所以我们在其中可以使用keep-alive
标签解决此问题:
直接使用keep-alive
包含需要缓存的组件出口,
其中他有三个属性:
include : 组件名数组,只有匹配的组件会被缓存。
exclude:组件名数组,任何匹配的组件都不会被缓存。
max :最多可以缓存多少组件实例。
使用如下:
<template><div class="h5-wrapper">//include的参数是一个组件名称数组。<keep-alive include="[index]" max="1"><router-view></router-view></keep-alive></div>
</template><script>
export default {name: "h5-wrapper",
}
</script>
keep-alive的使用会触发两个生命周期函数(了解)
activated 当组件被激活 (使用)的时候触发>进入页面触发
deactivated 当组件不被使用的时候触发>离开页面触发
在被缓存的组件下面就可以使用:
<template><div class="h5-wrapper"><div class="content">内容</div><nav class="tabbar"><a href="#/article">面经</a><a href="#/collect">收藏</a><a href="#/like">喜欢</a><a href="#/user">我的</a></nav></div>
</template><script>
export default {name: "LayoutPage",//进入页面时触发activated(){alert("欢迎来到首页")},//离开页面时触发deactivated(){}
}
</script>