1. 程式人生 > 實用技巧 >vue中路由守衛的理解

vue中路由守衛的理解

在實際專案中,路由跳轉前做一些驗證,比如登入驗證,是網站中的普遍需求。舉個例子,我們通常使用router.beforeEach註冊一個全域性前置守衛用來判斷登入的狀態:

let routesArr = [{
		path: '/home',
		name:"home",
		//redirect:"/about",//重定向
		//alias: '/index',//別名
		component: {
		template: `<div>
                <h1>這是首頁</h1>
                        </div>`				
			}
			}, {
			path: '/about',
			name:'about',
			component: {
			template: `<div>
                            <p>這是關於我們頁</p>
                        </div>`
			}
					}, {
			path: '/user/:name', // :name的作用是動態訪問一個地址,比如傳進來的是張三,就顯示張三的資訊
			name: 'user', // 這個name的作用是配合第95行新增屬性用的,二者必須一致 
			component: {
			template: `<div>

                            <!-- $route.params的作用是接收傳進來的名字,例如傳張三 name就是張三 -->
                            <p>我叫:{{ $route.params.name }}</p>

                            <!-- $route.query的作用是接收url上 ?age=18 這樣的引數 例如 router.html#/user/張三?age=18 -->
                            <p>我今年:{{ $route.query.age }} 歲了</p>

                            <div>
                                <!-- append是為了給下面的children子路由傳資料 -->
                                <router-link to="more" append> 更多資訊 </router-link>
                            </div>
                            
                            <!-- 這個router-view對應的就是children裡的template -->
                            <router-view></router-view>
                        </div>`
				},
				children: [{
				path: 'more',
				component: {
				template: `
                                <div>
                                使用者:{{ $route.params.name }} 的詳細資訊 abcd1234
                                </div>`
				}
				}]
				}

				];

				const vRouter = new VueRouter({
					routes: routesArr // 這裡要寫routes ,而不是routers,不然 <router-view> 沒資料
				})

  

vRouter.beforeEach((to, from, next) => {
    //這裡寫你的判斷邏輯
    const nextRoute = ['home', 'good-list', 'good-detail', 'cart', 'profile'];//需要登陸的頁面名
    let isLogin=  localEvent.get('web_login')||false;//獲取是否登入狀態
    // 未登入狀態;當路由到nextRoute指定頁時,跳轉至login
    if (nextRoute.indexOf(to.name) > -1) {  
      if (!isLogin) {
        //router.push({ name: 'login' });//可以直接跳轉名
        //next({ path: '/login', query: { redirect: to.fullPath } });//也可以跳轉路徑,並帶上重定向
      }
    }
    // 已登入狀態;當路由到login時,跳轉至home 
    if (to.name === 'login') {
      if (isLogin) {
        router.push({ name: 'home' });
      }
    }
    next();
});