1、route.js文件
import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const router = new Router({ routes: [ { path: '/', name: 'login', component: () => import('./views/login.vue') }, { path: '/schools', name: 'schools', component: () => import('./views/schools/main.vue') }, { path: '/main/:id', name: 'main', component: () => import('./views/report/main.vue'), redirect: '/main/:id/class', children: [ { path: '/main/:id/teacher', name: 'teacherMain', component: () => import('./views/teacher/main.vue'), }, { path: '/main/:id/teacher/:gradeId/:subjectId', name: 'teacherMain', component: () => import('./views/teacher/main.vue'), }, { path: '/main/:id/class', name: 'classMain', component: () => import('./views/class/main.vue'), }, ] }, { path: '**', // 錯誤路由 redirect: '/login' //重定向 } ] }) // 全局路由守衛 router.beforeEach((to, from, next) => { function getCookie(name) { let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)"); if (arr = document.cookie.match(reg)) return decodeURIComponent(arr[2]); else return null; } // to: Route: 即將要進入的目標 路由對象 // from: Route: 當前導航正要離開的路由 // next: Function: 一定要調用該方法來 resolve 這個鈎子。執行效果依賴 next 方法的調用參數。 let isLogin = getCookie("localtoken") !== null; // 是否登錄 // 未登錄狀態;當路由到nextRoute指定頁時,跳轉至login if (!isLogin && to.name !== 'login') { router.push({ name: 'login' }); } // 已登錄狀態;當路由到login時,跳轉至home if (to.name === 'login') { if (isLogin) { router.push('/schools'); } } next(); }); export default router;
2、路由跳轉
2.1 頁面跳轉
<router-link tag="nav" active-class="active" :to="'/main/'+schoolID+'/teacher'"> <a>教師</a> <i></i> </router-link> <router-link tag="nav" active-class="active" :to="'/main/'+schoolID+'/class'"> <a>班</a> <i></i> </router-link>
2.2 js方法跳轉
this.$router.push('/main/' + this.schoolID + '/teacher'); this.$router.push('/main/' + this.schoolID + '/teacher/' + this.nowGrade + "/" + this.nowSubject);
3、使用路由參數
watch: { //如果路由發生了變化,更新頁面數據 $route(to, from) { if (to.path !== from.path) { this.schoolID = this.$route.params.id; this.gradeId = this.$route.params.gradeId; this.subjectId = this.$route.params.subjectId; this.init(); } } }, data(){ return { schoolID: this.$route.params.id,//學校 id gradeId: this.$route.params.gradeId, subjectId: this.$route.params.subjectId, } },