How to use the vue global routing guard
In this article, the editor introduces in detail "how to use the vue global routing guard". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to use the vue global routing guard" can help you solve your doubts.
The specific steps are as follows:
1. First, create a new html project and install vue-router in the project
Npm install vue-router
2.vue-router is installed and vue and vue-router are introduced into the project.
Import Vue from 'vue'
Import Router from 'vue-router'
After 3.vue and vue-router are introduced, register a route in the project using the Vue.use method
Vue.use (VueRouter)
4. After the route is registered, define the route in the project and configure it
Export default new vueRouter ({
Routes: [{
Path:'/
Component: Index
}, {
Path:'/ Detail'
Component: Detail
Meta: {
RequireLogin: 2
}
}, {
Path:'/ Center'
Component: Center
Meta: {
RequireLogin: 1
}
}]
})
5. Finally, after the routing is configured, execute the following code in the project to use the global routing guard
Import router from'. / router'
Router.beforeEach ((to, from, next) = > {
Let token = window.localStorage.getItem ('token')
If (to.meta.requireLogin & & to.meta.requireLogin = 1) {
If (token) {
Next ()
} else {
Next ('/')
}
} else if (to.meta.requireLogin & & to.meta.requireLogin = 2) {
If (token) {
Next ('/ center')
} else {
Next ()
}
} else {
Next ()
}
})
After reading this, the article "how to use vue Global routing Guard" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, please follow the industry information channel.