路由元信息
meta:
每个路由的标识信息,是路由独有的一个信息,,,无论在路由中是否定义meta,,在组件中都可以通过this.$route.meta访问到,,如果没有定义,返回{}
在组件中:
通过this.$route.meta获取该组件的路由元信息
注意:如果没有在路由中定义meta,,,在组件中访问到的this.$route.meta为{},,,,访问到的值this.$route.meta.keepAlive为undefined
在路由中:
通过router.beforeEach((to,from,next)=>{
console.log(to.meta)
})
-----------------------------------------------
给每个路由的配置项多一个meta属性
meta:{
}
路由元信息用途
根据每个路由特有的信息
1.验证用户是否登录
2.设置标题
3.是否显示某个组件
4.组件是否缓存
……
验证用户是否登录,设置标题,举例:
import Vue from 'vue' import Router from 'vue-router' import Header from "../components/header" import Detail from "../components/goodsDetails" import Login from "../components/login" import goodsList from "../components/goodsList" Vue.use(Router) let router = new Router({ routes: [{ path: '/', redirect: Header }, { path: '/details/:name/:price/:id', name: 'details', component: Detail, meta: { isLogin: true, title: "详情页" } }, { path: '/login', name: 'login', component: Login, meta: { isLogin: false, title: "登录页" } }, { path: '/goodsList', name: "goodsList", component: goodsList, meta: { isLogin: false, title: "列表页" } } ] }) //判断是否登录 router.beforeEach((to, from, next) => { // console.log(to); //设置标题 document.title = to.meta.title; //判断是否登录 let token = true; if (to.meta.isLogin) { if (token) { next(); } else { next("/login") } } next(); }) export default router;
组件缓存
<keep-alive> <router-view></router-view> </keep-alive>
<!-- 这里是需要keepalive的 --> <keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <!-- 这里不会被keepalive --> <router-view v-if="!$route.meta.keepAlive"></router-view>
{
path: '',
name: '',
component: ,
meta: {keepAlive: true} // 这个是需要keepalive的
},
{
path: '',
name: '',
component: ,
meta: {keepAlive: false} // 这是不会被keepalive的
}
如果缓存的组件想要清空数据或者执行初始化方法,在加载组件的时候调用activated钩子函数,如下:
activated: function () { this.data = ''; }