Home > Web Front-end > JS Tutorial > Use vuex to store login status and disable browsing in non-login status. What are the specific methods?

Use vuex to store login status and disable browsing in non-login status. What are the specific methods?

亚连
Release: 2018-05-31 15:50:22
Original
2129 people have browsed it

Below I will share with you an article on how vuex implements the storage of login status and does not allow browsing in unlogged status. It has a good reference value and I hope it will be helpful to everyone.

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 the global pre-guard of vue-router. beforeEach, you can also use the route-exclusive guard beforeEnter.

Navigation guard

As the name suggests, the navigation guard provided by vue-router" is mainly used to guard navigation by jumping or canceling There are multiple opportunities to build into the route navigation process: globally, exclusive to a single route, or at the component level. Remember that changes to parameters or queries will not trigger entering/leaving navigation guards. You can do this by observing $route Object to respond to these changes, or use the guard within the component of beforeRouteUpdate.

Complete navigation parsing 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 the asynchronous routing component.

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) => {
 // ...
})
Copy after login

When a navigation is triggered, the global front guard is called in the order of creation. The guard is executed asynchronously, and the navigation is resolved before all guards are completed. Always waiting.

Each guard method receives three parameters:

to: Route: the target routing object to be entered

from: Route: the current navigation Route to leave

next: Function: This method must be called to resolve this hook. The execution effect depends on the calling parameters of the next method.

next(): Perform the next hook in the pipeline .If all hooks are executed, the navigation status is confirmed.

next(false): Interrupt the current navigation. If the browser URL changes (maybe the user manually or the browser backs off) button), then 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 guards

You can directly define the beforeEnter guard in the routing configuration:

const router = new VueRouter({
 routes: [
  {
   path: '/foo',
   component: Foo,
   beforeEnter: (to, from, next) => {
    // ...
   }
  }
 ]
})
Copy after login

There are other guards. For details, please see the official document https://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
})
Copy after login

In login.vue

Introduce import { mapActions,mapState } from 'vuex'

Then log in To change the state, 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;
          }
        })
      }
    }
  }
Copy after login

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();
  }
})
Copy after login

beforeEnter usage instance

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}表示把当前路由信息传递过去方便登录后跳转回来
     }
   } 
    }
   ]
})
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Node.js method example to implement registration email activation function

Webpack babel-loader file preprocessor Detailed explanation

jQuery implementation of news broadcast scrolling and fade-in and fade-out effects

The above is the detailed content of Use vuex to store login status and disable browsing in non-login status. What are the specific methods?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template