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();
});



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM