activated:路由组件被激活时触发。deactivated:路由组件失活时触发。作用: 对路由进行权限控制
分类: 全局守卫、独享守卫、组件内守卫
所有的路由都可以使用
// 全局前置路由守卫,每次初始化和路由切换之前被调用
// to:去哪儿
// from:从哪儿来
// next:跳转
router.beforeEach((to, from, next) => {
/* console.log(to, from)
if (to.name === "xinwen" || to.name === "xiaoxi") {
if (localStorage.getItem("school") === "尚硅谷") {
next()
} else {
alert("权限不足")
}
} else {
next()
} */
// document.title = to.meta.title || "Vue路由案例(Vue Router Demo)"
if (to.meta.isAuth) { // 判断是否需要鉴权
if (localStorage.getItem("school") === "尚硅谷") {
next()
} else {
alert("权限不足")
}
} else {
next()
}
})
// 全局后置路由守卫,每次初始化和路由切换之后被调用
// to:去哪儿
// from:从哪儿来
router.afterEach((to, from) => {
document.title = to.meta.title || "Vue路由案例(Vue Router Demo)"
})
某一个路由所独享的守卫,只有前置路由守卫
{
name: "xinwen",
path: 'news',
component: News,
meta: {isAuth: true, title: '新闻', },
// 进入之前
beforeEnter: (to, from, next) => {
if (to.meta.isAuth) { // 判断是否需要鉴权
if (localStorage.getItem("school") === "尚硅谷") {
next()
} else {
alert("权限不足")
}
} else {
next()
}
}
},
组件所独有的路由守卫,通过路由规则进入时和离开时调用
beforeRouteEnter (to, from, next) {
if (to.meta.isAuth) { // 判断是否需要鉴权
if (localStorage.getItem("school") === "尚硅谷") {
next()
} else {
alert("权限不足")
}
} else {
next()
}
},
// 通过路由规则离开该组件时被调用
beforeRouteLeave (to, from, next) {
next()
}
http://localhsot:8080/#/
#号,不美观。使用命令:
npm run build
# 或
yarn run build
打包之后会生成一个dist的文件夹,将里面的内容部署上线
.babelrc文件,配置在babel.config.js文件中["es2015", { "modules": false }]在新版的vue-cli上使用["@babel/preset-env", { "modules": false }]