Home >Web Front-end >JS Tutorial >How to use vue router+vuex to realize home page login verification judgment
This time I will show you how to use vue router vuex to realize home page login verification judgment, and how to use vue router vuex to realize home page login verification judgment. What are the precautions?The following is a practical case, let’s take a look .
1.vue router
RoutingThe first thing we think of is router.before Each is preceded by Navigation guards. This method accepts three parameters to from next.
The to parameter is the routing path that is about to jump, from is the route that the current navigation is about to leave, and the next method is used to resolve this hook.
The following is an example of a judgment written at work:
router.beforeEach(async (to, from, next) => { const { name, meta } = to; const { requireLogin } = meta; if (name === 'login') { // 如果是登录页则用next方法resolve掉这个钩子,如果不是,进行到下一个判断 return next(); } const needLogin = requireLogin && !store.getters.user.isLogin; // 从store中读取是否获取了已登录的信息 if (needLogin) { return next({ // 如果没有则跳转到登录页,将当前路由路径放到参数中 name: 'login', params: { back: to }, }); } return next(); });
2. this.$router and this.$route this.$router.push and this .$router.replace
After completing the login request on the login page, perform the following operations
Get the parameters of the previous path stored in the path, and then jump to the page
loginSuccess() { const { params: { back } } = this.$route; const route = back || { name: 'home' }; const { name, params, query } = route; this.$router.replace({ name, params, query }); },
In the above code, two concepts that we often confuse appear:
We know that this.$router is a router instance and can be used to directly access routing. We call each object in the router configuration a routing record, and this.$route is exposed to access each routing record. Therefore, when we obtain parameters, we use this.$route, and when we jump to routes, we use this.$router.
In the upper code, we use replace instead of push to jump the route. The difference between the two is whether a record will be generated in the history. replace does not add a new record, but directly replaces the routing record.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to build a webpack react development environment
How to use JS to call the local camera
The above is the detailed content of How to use vue router+vuex to realize home page login verification judgment. For more information, please follow other related articles on the PHP Chinese website!