1、导入
//配置路由相关的信息
import Vue from 'vue'
import vuerouter from 'vue-router'
2、配置路由
Vue.use(vuerouter)
//采用懒加载 导入路由
const Home = () =>
import ('../components/Home')
const About = () =>
import ('../components/About')
const User = () =>
import ('../components/User')
const HomeNews = () =>
import ('../components/HomeNews')
const HomeMessage = () =>
import ('../components/HomeMessage')
const Profile = () =>
import ('../components/Profile')
const router = new vuerouter({
routes: [{
path: '',
name:'主页',
redirect: '/home' //重定向
,
meta: {
title: '首页'
}
},
{
path: '/home',
name:'主页',
component: Home,
meta: {
title: '首页'
},
//创建子
children: [
{
path: 'news',
component: HomeNews
},
{
path: 'message', //这么的名称要与 <router-link to="/Home/message"> 一致
component: HomeMessage
}
]
},
{
path: '/about',
component: About,
meta: {
title: '关于'
}
},
{
path: '/user/:userid', //可添加配置的用户id
component: User,
meta: {
title: '用户'
}
},
{
path: '/profile',
component: Profile,
meta: {
title: '档案'
}
}
], //名称必须为 routes
mode: 'history', //设置html的模式 及hit 模式
linkActiveClass: 'active' //自动绑定 属性
})
3、设置全局导航守卫
//全局导航守卫 回调前
router.beforeEach((to, from, next) => {
//处理token 判断是否登入状态 ,如果是正常运行 ,如果不是 先判断token 是否存在
if (to.path === '/login') {
next()
}
else {
const token = localStorage.getItem('token')
if (!token) {
//提示 ,必须导入el - ui
Message.warning('请先登入!')
router.push({ path: 'login' })
return
}
}
// 方式1 通过路由导航进行获取 设置页面title 的名称 需要在路由里面配置meta属性
document.title = to.matched[0].meta.title
//方式2 通过调用路由配置里面的name 属性
document.title = to.name
next()
})
// 全局守卫 回调后
router.afterEach((to, from) => {
})
4、如果需要在请求头里面添加token的化:直接上代码
在Main.js中添加
axios.interceptors.request.use(config =>{
config.headers = {
'Content-Type':'application/json;charset=UTF-8',
'Token': window.sessionStorage.getItem('token') //获取登录时保存本地的token
}
return config
})