溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

vuex+axios如何實(shí)現(xiàn)登錄驗(yàn)證并且保存登錄狀態(tài)

發(fā)布時(shí)間:2021-07-09 12:02:01 來源:億速云 閱讀:1032 作者:小新 欄目:web開發(fā)

小編給大家分享一下vuex+axios如何實(shí)現(xiàn)登錄驗(yàn)證并且保存登錄狀態(tài),希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

第一步:安裝axios 、vuex npm i -s axios npm i -s vuex 執(zhí)行這兩句 ,vue等環(huán)境搭建就不廢話了

第二步:配置main.js文件

vuex+axios如何實(shí)現(xiàn)登錄驗(yàn)證并且保存登錄狀態(tài)

上圖不上碼,菊花萬人捅,附上代碼

// 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' //引入狀態(tài)管理
 
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';
//注冊(cè)狀態(tài)管理全局參數(shù)
var store = new Vuex.Store({
 state:{
 token:'',
 userID:'',
 },
 mutations: {
 //寫法與getters相類似
 //組件想要對(duì)于vuex 中的數(shù)據(jù)進(jìn)行的處理
 //組件中采用this.$store.commit('方法名') 的方式調(diào)用,實(shí)現(xiàn)充分解耦
 //內(nèi)部操作必須在此刻完成(同步)
 [ADD_COUNT] (state, token) { // 第一個(gè)參數(shù)為 state 用于變更狀態(tài) 登錄
  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');//獲取本地存儲(chǔ)的token
 
 if (to.meta.requireAuth) { // 判斷該路由是否需要登錄權(quán)限
 if (store.state.token !== "") { // 通過vuex state獲取當(dāng)前的token是否存
  next();
 }
 else {
  next({
  path: '/login',
  query: {redirect: to.fullPath} // 將跳轉(zhuǎn)的路由path作為參數(shù),登錄成功后跳轉(zhuǎn)到該路由
  })
 }
 }
 else {
 next();
 }
})
 
router.afterEach(route => {
 iView.LoadingBar.finish();
});
 
 
/* eslint-disable no-new */
new Vue({
 el: '#app',
 router,
 store, //注冊(cè)組件
 components: { App },
 template: '<App/>'
}) ;

第三步:進(jìn)行登錄 操作,調(diào)用main.js 中定義好的修改token的方法[ADD_COUNT]

vuex+axios如何實(shí)現(xiàn)登錄驗(yàn)證并且保存登錄狀態(tài)

附上請(qǐng)求部分代碼

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('登錄失敗,錯(cuò)誤:'+ err);
 this.$Loading.error();
}.bind(this))

差點(diǎn)忘記了一點(diǎn),在router中要配置需要驗(yàn)證是否登錄的請(qǐng)求

vuex+axios如何實(shí)現(xiàn)登錄驗(yàn)證并且保存登錄狀態(tài)

附上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',//登錄頁(yè)
  name: 'Login',
  component: Login
 },
 {
  path: '/',//首頁(yè)
  name: 'Main',
  component: Main,
  meta: {
  requireAuth: true, // 添加該字段,表示進(jìn)入這個(gè)路由是需要登錄的
  },
 },
 { path: '*', component: P404 } //這里是保證錯(cuò)誤地址會(huì)跳轉(zhuǎn)到404界面進(jìn)行提示
 ]
})

看完了這篇文章,相信你對(duì)“vuex+axios如何實(shí)現(xiàn)登錄驗(yàn)證并且保存登錄狀態(tài)”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI