vue router路由导航
2019-04-28 本文已影响0人
Gino_Li
定义导航
<router-link to="/">组件一</router-link> <!-- 默认路径:进入页面显示的页面 -->
<router-link to="/testB">组件二</router-link>
需要加上router-view
,显示组件内容
<router-view></router-view>
配置router.js文件
1.引入
import Vue from 'vue'
import Router from 'vue-router'
2.引用插件router
//在引用插件时需要通过Vue.use()来使用
Vue.use(Router)
3.定义路由信息
export default new Router({
mode:'history', //历史模式,去除地址栏上的#号
routes:[
{//默认路由
path:'/',
component:Home,
name:'home',
meta:{ //路由元信息
isLogin:true
}
},
{
path:'/home',
component:Home,
name:'home',
alias:"/h", //别名
meta:{ //路由元信息
isLogin:true
}
}],
{ //定义404页面
path:'*',//匹配所有
name:"noFound",
component:()=>import("./views/notFound.vue")
},
})
路由元信息
通常可以用来做登录判断
比如:一个网站有些页面是需要登录后才可以进入的
routes:[
{
path:'/',
component:Home,
name:'home',
meta:{ //路由元信息
isLogin:true
}
}
}
获取meta信息
<template>
<div>
<h1>{{ $route.meta.isLogin}}</h1>
</div>
</template>
导航守卫中获取
1.直接获取
router.beforeEach((to, from, next) => {
window.document.title = to.meta.title;
next();
})
2.通过$route.matched
遍历
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// this route requires auth, check if logged in
// if not, redirect to login page.
if (!auth.loggedIn()) {
next({
path: '/login',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next() // 确保一定要调用 next()
}
})
路由引用组件方式
1.全局引入
适合主页面和登录页面,预先加载
import Home from './views/Home.vue'
{
path:'/',
name:'home',
component:Home
2.路由懒加载(局部引入)
当进入页面时才进行加载
{
path:'/contact:uid',
component:()=>import('./views/Contact.vue'),
name:'contact',
}