vue-router 路由导航+卫士
程序员文章站
2022-04-12 09:51:55
...
简单记录一下,随时查阅官方文档
SPA 中,页面跳转控制都在前端做了
vue router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Login from '@/view/Login'
import Index from '@/view/Index'
import Manage from '@/view/Manage'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
name: 'Index',
component: Index,
redirect: '/login'
},
{
path: '/helloworld',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/manage',
name: 'manage',
component: Manage
},
{
path: '/login',
name: 'login',
component: Login
}
]
})
//回调方法,在跳转前执行
router.beforeEach((to, from, next) => {
// to 及将要进入的目标的路由对象
// from 当前导航即将离开的路由对象
// next 调用该方法后,才能进入下一个钩子
if(to.name=="login"){
next()
}
console.log("to.name "+to.name)
console.log("from.name "+from.name)
//登录成功之后就可以进入页面
if(localStorage.getItem("token")){
next();
}else{
next('/login')
}
})
export default router;
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
//这样方便使用
window.router = router
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
Login.vue
login() {
if (this.user === "admin" && this.pwd === "123") {
window.localStorage.setItem("token", "11");
this.statusC = "已登录";
router.push('/manage');
} else {
window.localStorage.clear();
this.statusC = "登录失败";
}
}