Make writing a habit together! This is the 11th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.
preface
This paper records some problems encountered in the use of VUe2 vue-Router.
The problem record
Application of route guard
There are three types of routing guards according to the binding position of routing guards
Global guard
beforeEach/beforeResolve/afterEach
Route exclusive guard
beforeEnter
Guards within components
beforeRouteEnter/beforeRouteUpdate/beforeRouteLeave
Its complete navigation parsing process, see the official documentation of the description is like this:
- Navigation is triggered.
- Called in a deactivated component
beforeRouteLeave
The guards.- Call global
beforeEach
The guards.- Called in a reused component
beforeRouteUpdate
Guard (+ 2.2).- Called in the routing configuration
beforeEnter
.- Parse the asynchronous routing component.
- Called in the active component
beforeRouteEnter
.- Call global
beforeResolve
Guard (+ 2.5).- Navigation confirmed.
- Call global
afterEach
Hook.- Trigger a DOM update.
- Call with the created instance
beforeRouteEnter
Guard passnext
The callback function of.
Here are some examples of common hooks in action:
BeforeRouteLeave: Reminds the user whether to save the message or automatically save the draft for the user before jumping to the page.
BeforeEach: Determines whether to log in to the vm and whether to have permissions, and performs operations such as switching to login, applying for permissions, and processing permissions.
BeforeRouteUpdate: reinitializes and loads data when re-entering the same page.
BeforeRouteEnter: Gets information about the previous page of the current page. For example, if we are on the login page and want to redirect to the previous page after login, we can get this hook. Note: Here, no! Can!!!! Get component instance this because the new component has not yet been created. However, you can pass a callback to Next to access the instance, which will be executed once the instance is created.
beforeRouteEnter (to, from, next) {
next(vm= > {
// Access component instances through 'VM'})}Copy the code
Several other route guards, which I don’t use very often, are welcome to leave comments.
Dynamic routing implements permission control
Application scenario: The management terminal displays different menu bars based on different permissions and prevents users without permissions from accessing certain pages.
Solution: Before entering the route, we do an interception to determine whether the page permission needs to be processed first, and then whether the page permission has been processed. If the answer is “yes”, we do not need to do processing. Otherwise, request the interface, obtain the permission menu of the current user, dynamically add a route to the router based on the information returned in the background, and then re-enter the route. (In this case, the blocked access is a newly added route and the access failure occurs.)
Look at the following pseudocode:
router.beforeEach((to, from, next) = > {
if (needAuthority(to.name)) { // Pages that do not need to determine permissions are not processed
next()
return
}
if (alreadyGetAuthorityMenu) { // Permission menu already processed, no longer processed
next()
return
}
handleAuthority().then(() = >{ next({ ... to,replace: true }) // Process permission menu interface succeeded, dynamic route has been added, enter route again
}).catch(() = > {
console.log('Request permission menu interface error')
next()
})
})
Copy the code
In the handleAuthority we do these things
- Check whether the user has the permission. If the user does not have the permission, go to the permission application page
- According to the permissions list sent from the background, use
router.addRoutes(routes: Array)
This API dynamically adds routes to the Router for pages requiring permission control. - Add a backstop page to the router dynamically, either a “no permission” page or a simple 404 page.
Note that after dynamically adding routes, next({… To, replace: true}) re-enter the route, otherwise, if the intercepted page route is a route you added later, the new route will not be accessible.
Route parameters in hash mode are interfered
Application scenario: For example, wechat sharing link will be added, like ‘? From = singleMessage&isappInstalled =0’. When we use hash mode routing and params mode to transmit parameters, we will be disturbed by external parameters, so that the page cannot be accessed or the parameters cannot be obtained. Using dynamic routing parameters is a better choice.
const router = new VueRouter({
routes: [
// Dynamic path parameters start with a colon
{ path: '/user/:id'.component: User }
]
})
const userId = '123'
// Two jump modes
router.push({ name: 'user'.params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// Params does not work here
router.push({ path: '/user'.params: { userId }}) // -> /user
Copy the code
Further, we can decouple the component from the route using props. By defining the ID of the props in the component, we can get the parameters passed.
const router = new VueRouter({
routes: [{path: '/user/:id'.component: User, props: true}]})Copy the code
Redirect to component route without refreshing?
Application scenario: Switches to a page of the same component with different parameters and expects to refresh the page.
Solution: In beforeRouteUpdate, we can re-execute the code to enter the page, but if we need to initialize all variables, we will miss it. It is easier to listen for route changes, which is this.$router.go(0) refresh.
/ / recommend
beforeRouteUpdate(to, from, next) {
// Reload the data
next();
},
Copy the code
watch: {
'$route'(to, from) {
this.$router.go(0)}}Copy the code
Past oliver
Say goodbye to Bad Code
2022 Code Specification Best Practices (with Web and applets Best configuration examples)
【 Front-end Exploration 】 Say goodbye to bad code! Encapsulate network requests in the chain of responsibility pattern
【 Front-end Exploration 】 Say goodbye to bad code # 2! Encapsulate sharing components with policy patterns
The code of life
[Thinking on three years of front-end development] How to read requirements effectively?
Front end step pit must see guide
[Front-end exploration] Best practices for image loading optimization
[Front-end exploration] Exploration of mobile terminal H5 to generate screenshot posters
[Front-end Exploration] H5 to obtain user positioning? This one is enough
【 Front-end exploration 】 The exploration of wechat small program jump — Why does open label exist?