search
HomeWeb Front-endJS TutorialUse vuex to store login status and disable browsing in non-login status. What are the specific methods?

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

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) => {
    // ...
   }
  }
 ]
})

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
})

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;
          }
        })
      }
    }
  }

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

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!

Statement
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
如何查看服务器状态如何查看服务器状态Oct 09, 2023 am 10:10 AM

查看服务器状态的方法有使用命令行工具、图形界面工具、监控工具、日志文件和远程管理工具等。详细介绍:1、使用命令行工具,在Linux或Unix服务器上,可以使用命令行工具来查看服务器的状态;2、使用图形界面工具,对于具有图形界面的服务器操作系统,可以使用系统提供的图形界面工具来查看服务器状态;3、使用监控工具,可以使用专门的监控工具来实时监视服务器的状态等等。

如何在安卓手机上的WhatsApp上离线显示如何在安卓手机上的WhatsApp上离线显示Jul 14, 2023 am 08:21 AM

想要显示为“离线”或不想在WhatsApp上与您的朋友分享您的当前状态?有一个简单而巧妙的技巧可以做到这一点。您可以调整WhatsApp设置,以便您的朋友或其他人无法在其中看到您的当前状态(离线或上次看到)。如何在您的WhatsApp状态栏上显示为离线状态?这是一个非常简单和简化的过程。因此,请立即执行以下步骤。步骤1–在手机上打开WhatsApp。步骤2–点击⋮并选择打开“设置”。第3步–打开“隐私”设置以访问它。第4步–在该隐私页面上,打开“上次查看和在线”设置以访问该设置。步骤5–将“谁可

Vue2.x中使用Vuex管理全局状态的最佳实践Vue2.x中使用Vuex管理全局状态的最佳实践Jun 09, 2023 pm 04:07 PM

Vue2.x是目前最流行的前端框架之一,它提供了Vuex作为管理全局状态的解决方案。使用Vuex能够使得状态管理更加清晰、易于维护,下面将介绍Vuex的最佳实践,帮助开发者更好地使用Vuex以及提高代码质量。1.使用模块化组织状态Vuex使用单一状态树管理应用的全部状态,将状态从组件中抽离出来,使得状态管理更加清晰易懂。在具有较多状态的应用中,必须使用模块

Vue3中Vuex怎么使用Vue3中Vuex怎么使用May 14, 2023 pm 08:28 PM

Vuex是做什么的?Vue官方:状态管理工具状态管理是什么?需要在多个组件中共享的状态、且是响应式的、一个变,全都改变。例如一些全局要用的的状态信息:用户登录状态、用户名称、地理位置信息、购物车中商品、等等这时候我们就需要这么一个工具来进行全局的状态管理,Vuex就是这样的一个工具。单页面的状态管理View–>Actions—>State视图层(view)触发操作(action)更改状态(state)响应回视图层(view)vuex(Vue3.

在Vue应用中使用vuex时出现“Error: [vuex] do not mutate vuex store state outside mutation handlers.”怎么解决?在Vue应用中使用vuex时出现“Error: [vuex] do not mutate vuex store state outside mutation handlers.”怎么解决?Jun 24, 2023 pm 07:04 PM

在Vue应用中,使用vuex是常见的状态管理方式。然而,在使用vuex时,我们有时可能会遇到这样的错误提示:“Error:[vuex]donotmutatevuexstorestateoutsidemutationhandlers.”这个错误提示是什么意思呢?为什么会出现这个错误提示?如何解决这个错误?本文将详细介绍这个问题。错误提示的含

深入了解vuex的实现原理深入了解vuex的实现原理Mar 20, 2023 pm 06:14 PM

当面试被问vuex的实现原理,你要怎么回答?下面本篇文章就来带大家深入了解一下vuex的实现原理,希望对大家有所帮助!

在Vue应用中使用vuex时出现“Error: [vuex] unknown action type: xxx”怎么解决?在Vue应用中使用vuex时出现“Error: [vuex] unknown action type: xxx”怎么解决?Jun 25, 2023 pm 12:09 PM

在Vue.js项目中,vuex是一个非常有用的状态管理工具。它可以帮助我们在多个组件之间共享状态,并提供了一种可靠的方式来管理状态的变化。但在使用vuex时,有时会遇到“Error:[vuex]unknownactiontype:xxx”的错误。这篇文章将介绍该错误的原因及解决方法。1.错误原因在使用vuex时,我们需要定义一些actions和mu

在Vue应用中使用vuex时出现“TypeError: Cannot read property 'xxx' of undefined”怎么解决?在Vue应用中使用vuex时出现“TypeError: Cannot read property 'xxx' of undefined”怎么解决?Aug 18, 2023 pm 09:24 PM

在Vue应用中使用Vuex是非常常见的操作。然而,偶尔在使用Vuex时会遇到错误信息“TypeError:Cannotreadproperty'xxx'ofundefined”,这个错误信息的意思是无法读取undefined的属性“xxx”,导致了程序的错误。这个问题其实产生的原因很明显,就是因为在调用Vuex的某个属性的时候,这个属性没有被正确

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.