The content of this article is about the implementation of navigation guards under vue.js global routing. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In general terms, the navigation guard is a controller that controls which routes users can enter and which routes they cannot enter. It is also the controller that manages routing.
For example, when you first enter the website, When you want to write a blog, you must log in first before you can enter the blog writing; the login interface is like a route that you can enter, and the blog is a route that you cannot enter. After you log in, the controller will give you permission to enter the blog. Routing, this is the purpose of Navigation Guard
Global routing must be created under the main.js file
If you want to use Navigation GuardYou must have routing first
//main.js const router= new VueRouter({ routes:[ {path:'/',name:'home',component:Home}, {path:'/menu',name:'menu',component:Menu}, {path:'/admin',name:'admin',component:Admin}, {path:'/about',name:'about',component:About,redirect: {name:'contactLink'},children:[ //二级路由 {path:'/about/contact',name:'contactLink',component:Contact}, {path:'/history',name:'historyLink',component:History}, {path:'/delivery',name:'deliveryLink',component:Delivery}, {path:'/orderingGuide',name:'orderingGuideLink',component:OrderingGuide,redirect:{name:'phonelink'},children: [ //三级路由 {path:'/phone',name:'phonelink',component:Phone}, {path:'/name',name:'namelink',component:Name} ]}, ]}, {path:'/login',name:'login',component:Login}, {path:'/register',name:'register',component:Register}, {path:'*',redirect:'/'} ], mode:"history" });
Use the beforeEach() method of the routing object router above to implement the navigation guard
//main.js //to:跳转到的路由 from:从哪个路由离开 next:显示函数 router.beforeEach((to,from,next)=>{ if(to.path == '/login' || to.path == '/register'){ next(); }else{ alert("请先登录"); next('/login'); } });
'/login' '/register' to define the routing address for yourself
to.path is the routing address to jump to
next() is to display the current routing content
next('/login') jumps to the specified route and displays the specified route Content
To information that can be obtained by the object (console.log(to) view)
##Related recommendations:VueRouter 'sGuide Navigationkeeper伟How to use
Vue路Bydynamic redirection and guide Navigationkeeper卫
The above is the detailed content of Implementation of navigation guard under vue.js global routing. For more information, please follow other related articles on the PHP Chinese website!