Home >Web Front-end >JS Tutorial >Vuex implements different permissions for logged in and non-logged in
This time I will bring you vuex to implement different permissions for login and non-login, and vuex to implement different permissions for login and non-login. What are the precautions. Here is a practical case. Let’s take a look. .
The basic idea is to use vuex state management to store the login status (actually, it means to store a value, such as token), and then judge the login status before routing jump. You can use vue-router's global front guard beforeEach, or you can use routing Exclusive guard beforeEnter.
Navigation Guard
As the name suggests, the navigation guards provided by vue-router are mainly used to guard navigation by jumping or canceling. There are many opportunities to be embedded in the route navigation process: global, Exclusive to a single route, or component-level. Remember that changes to parameters or queries do not trigger enter/leave navigation guards. You can do this by observing $route Object to handle these changes, or use a beforeRouteUpdate guard within the component.
Complete navigation analysis process
1. Navigation is triggered.
2. Call the leave guard in the deactivated component.
3. Call the global beforeEach guard.
4. Call the beforeRouteUpdate guard (2.2) in the reused component.
5. Call beforeEnter in the routing configuration.
6. Parse asynchronous routing components.
7. Call beforeRouteEnter in the activated component.
8. Call the global beforeResolve guard (2.5).
9. Navigation is confirmed.
10. Call the global afterEach hook.
11. Trigger DOM update.
12. Use the created instance to call the callback function passed to next in the beforeRouteEnter guard.
Global Guard
You can use router.beforeEach to register a global front guard
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
When a navigation is triggered, global front guards are called in the order they were created. Guards are parsed and executed asynchronously. At this time, the navigation is waiting until all guards are resolved.
Each guard method receives three parameters:
to: Route: The target routing object that is about to enter
from: Route: The route that the current navigation is leaving
next: Function: This method must be called to resolve this hook. The execution effect depends on the calling parameters of the next method.
next(): Proceed to the next hook in the pipeline. If all hooks are executed, the navigation status is confirmed.
next(false): Interrupt current navigation. If the browser's URL changes (perhaps manually by the user or by the browser's back button), the URL address will be reset to the address corresponding to the from route.
next('/') or next({ path: '/' }): Jump to a different address. The current navigation is interrupted and a new navigation is started.
next(error):(2.4.0) If the parameter passed to next is an Error instance, the navigation will be terminated and the error will be passed to the callback registered by router.onError().
Make sure to call the next method, otherwise the hook will not be resolved.
Route exclusive guard
You can define the beforeEnter guard directly on the routing configuration:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] })
There are other guards. For details, please see the official documentationhttps://router.vuejs.org/zh-cn/advanced/navigation-guards.html
After installing vuex
Create store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex); const state = { isLogin: 0 } const mutations = { changeLogin(state,status){ state.isLogin = status; } } const actions = { loginAction({commit}){ commit('changeLogin',1); } } export default new Vuex.Store({ state, actions, mutations })
login.vue中
Introduce import { mapActions,mapState } from 'vuex'
Then change the login status, base_url is the path
export default { name: 'Login', data(){ return{ loginForm: { username: '', password: '', }, rules: { username: [ { required: true, message: '请输入用户名', trigger: 'blur' }, ], password: [ { required: true, message: '请输入密码', trigger: 'blur' } ], }, showLogin: false } }, mounted(){ this.showLogin = true; }, computed: { ...mapState(['isLogin']) }, methods: { ...mapActions(['loginAction']), submitForm(formName){ this.$refs[formName].validate((valid) => { if(valid){ if(this.loginForm.username == 'aaa' && this.loginForm.password == '111'){ console.log('验证通过'); this.loginAction(); this.$router.push('manage'); }else{ console.log('账号密码出错'); // this.$message.error('账号密码出错'); this.$message({ type: 'error', message: '账号密码出错' }); } console.log('请求地址: ' + base_url); }else{ console.log('验证失败'); return false; } }) } } }
Next, just use the routing guard
beforeEach usage example
router.beforeEach((to,from,next)=>{ if(to.meta.check){ var check = async function(){ const result = await checkUser(); if(result.status == 0){ next(); }else{ alert('用户未登录'); next({path: '/login'}); } } check(); //后台验证session }else{ next(); } })
beforeEnter usage example
export default new Router({ routes: [ { path: '/login', component: Login }, { path: '/manage', name: '', component: Manage, beforeEnter: (to,from,next)=> { //导航守卫 console.log(to) console.log(from) if(store.state.isLogin == 1){ console.log('用户已经登录'); next(); }else{ console.log('用户未登录'); next({path: '/login',query:{ Rurl: to.fullPath}}); //未登录则跳转到登陆界面,query:{ Rurl: to.fullPath}表示把当前路由信息传递过去方便登录后跳转回来 } } } ] })
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of Vuex implements different permissions for logged in and non-logged in. For more information, please follow other related articles on the PHP Chinese website!