温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vuex+axios如何实现登录验证并且保存登录状态

发布时间:2021-07-09 12:02:01 来源:亿速云 阅读:1026 作者:小新 栏目:web开发

小编给大家分享一下vuex+axios如何实现登录验证并且保存登录状态,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

第一步:安装axios 、vuex npm i -s axios npm i -s vuex 执行这两句 ,vue等环境搭建就不废话了

第二步:配置main.js文件

vuex+axios如何实现登录验证并且保存登录状态

上图不上码,菊花万人捅,附上代码

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import iView from 'iview';
import 'iview/dist/styles/iview.css';
import locale from 'iview/dist/locale/en-US';
import VueParticles from 'vue-particles';
import axios from 'axios' ;
import Vuex from 'vuex' //引入状态管理
 
Vue.use(VueParticles) ;
Vue.use(iView, { locale });
Vue.config.productionTip = false ;
Vue.prototype.$http = axios ;
Vue.use(Vuex) ;
 
 
const ADD_COUNT = 'ADD_COUNT'; // 用常量代替事件类型,使得代码更清晰
const REMOVE_COUNT = 'REMOVE_COUNT';
//注册状态管理全局参数
var store = new Vuex.Store({
 state:{
 token:'',
 userID:'',
 },
 mutations: {
 //写法与getters相类似
 //组件想要对于vuex 中的数据进行的处理
 //组件中采用this.$store.commit('方法名') 的方式调用,实现充分解耦
 //内部操作必须在此刻完成(同步)
 [ADD_COUNT] (state, token) { // 第一个参数为 state 用于变更状态 登录
  sessionStorage.setItem("token", token);
  state.token = token;
 },
 [REMOVE_COUNT] (state, token) { // 退出登录
 
  sessionStorage.removeItem("token", token);
 
  state.token = token;
 },
 }
});
 
 
router.beforeEach((to, from, next) => {
 iView.LoadingBar.start();//loadong 效果
 
 store.state.token = sessionStorage.getItem('token');//获取本地存储的token
 
 if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
 if (store.state.token !== "") { // 通过vuex state获取当前的token是否存
  next();
 }
 else {
  next({
  path: '/login',
  query: {redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
  })
 }
 }
 else {
 next();
 }
})
 
router.afterEach(route => {
 iView.LoadingBar.finish();
});
 
 
/* eslint-disable no-new */
new Vue({
 el: '#app',
 router,
 store, //注册组件
 components: { App },
 template: '<App/>'
}) ;

第三步:进行登录 操作,调用main.js 中定义好的修改token的方法[ADD_COUNT]

vuex+axios如何实现登录验证并且保存登录状态

附上请求部分代码

this.$http({
 method: 'get',
 url: '/api/login',
}).then(function(res){
 var json = res.data
 console.log(json.data);
 this.$Message.success('Success!');
 
 this.$store.commit('ADD_COUNT', json.data.token);
 
 let clock = window.setInterval(() => {
 this.totalTime-- ;
 if (this.totalTime < 0) {
  window.clearInterval(clock) ;
  this.$Loading.finish();
  this.$router.push('/') ;
 }
 },1000)
}.bind(this)).catch(function(err){
 this.$Message.error('登录失败,错误:'+ err);
 this.$Loading.error();
}.bind(this))

差点忘记了一点,在router中要配置需要验证是否登录的请求

vuex+axios如何实现登录验证并且保存登录状态

附上router/index.js 代码

import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/Login/Login'
import P404 from '@/components/404/404'
import Main from '@/components/Main'
 
Vue.use(Router)
 
export default new Router({
 mode: 'history',
 routes: [
 {
  path: '/login',//登录页
  name: 'Login',
  component: Login
 },
 {
  path: '/',//首页
  name: 'Main',
  component: Main,
  meta: {
  requireAuth: true, // 添加该字段,表示进入这个路由是需要登录的
  },
 },
 { path: '*', component: P404 } //这里是保证错误地址会跳转到404界面进行提示
 ]
})

看完了这篇文章,相信你对“vuex+axios如何实现登录验证并且保存登录状态”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI