vuex + axios 做登录验证 并且保存登录状态

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

第二步:配置main.js文件  

附上代码

 


 
 
  1. // The Vue build version to load with the `import` command
  2. // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
  3. import Vue from 'vue'
  4. import App from './App'
  5. import router from './router'
  6. import iView from 'iview';
  7. import 'iview/dist/styles/iview.css';
  8. import locale from 'iview/dist/locale/en-US';
  9. import VueParticles from 'vue-particles';
  10. import axios from 'axios' ;
  11. import Vuex from 'vuex' //引入状态管理
  12. Vue.use(VueParticles) ;
  13. Vue.use(iView, { locale });
  14. Vue.config.productionTip = false ;
  15. Vue.prototype.$http = axios ;
  16. Vue.use(Vuex) ;
  17. const ADD_COUNT = 'ADD_COUNT'; // 用常量代替事件类型,使得代码更清晰
  18. const REMOVE_COUNT = 'REMOVE_COUNT';
  19. //注册状态管理全局参数
  20. var store = new Vuex.Store({
  21. state:{
  22. token: '',
  23. userID: '',
  24. },
  25. mutations: {
  26. //写法与getters相类似
  27. //组件想要对于vuex 中的数据进行的处理
  28. //组件中采用this.$store.commit('方法名') 的方式调用,实现充分解耦
  29. //内部操作必须在此刻完成(同步)
  30. [ADD_COUNT] (state, token) { // 第一个参数为 state 用于变更状态 登录
  31. sessionStorage.setItem( "token", token);
  32. state.token = token;
  33. },
  34. [REMOVE_COUNT] (state, token) { // 退出登录
  35. sessionStorage.removeItem( "token", token);
  36. state.token = token;
  37. },
  38. }
  39. });
  40. router.beforeEach( (to, from, next) => {
  41. iView.LoadingBar.start(); //loadong 效果
  42. store.state.token = sessionStorage.getItem( 'token'); //获取本地存储的token
  43. if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
  44. if (store.state.token !== "") { // 通过vuex state获取当前的token是否存
  45. next();
  46. }
  47. else {
  48. next({
  49. path: '/login',
  50. query: { redirect: to.fullPath} // 将跳转的路由path作为参数,登录成功后跳转到该路由
  51. })
  52. }
  53. }
  54. else {
  55. next();
  56. }
  57. })
  58. router.afterEach( route => {
  59. iView.LoadingBar.finish();
  60. });
  61. /* eslint-disable no-new */
  62. new Vue({
  63. el: '#app',
  64. router,
  65. store, //注册组件
  66. components: { App },
  67. template: '<App/>'
  68. }) ;

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

附上请求部分代码

 


 
 
  1. this.$http({
  2. method: 'get',
  3. url: '/api/login',
  4. }).then(function(res){
  5. var json = res. data
  6. console.log(json. data);
  7. this.$Message.success( 'Success!');
  8. this.$store.commit( 'ADD_COUNT', json. data.token);
  9. let clock = window.setInterval(() => {
  10. this.totalTime-- ;
  11. if ( this.totalTime < 0) {
  12. window.clearInterval(clock) ;
  13. this.$Loading.finish();
  14. this.$router.push( '/') ;
  15. }
  16. }, 1000)
  17. }.bind( this)). catch(function(err){
  18. this.$Message.error( '登录失败,错误:'+ err);
  19. this.$Loading.error();
  20. }.bind( this))

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

附上router/index.js  代码

 


 
 
  1. import Vue from 'vue'
  2. import Router from 'vue-router'
  3. import Login from '@/components/Login/Login'
  4. import P404 from '@/components/404/404'
  5. import Main from '@/components/Main'
  6. Vue.use(Router)
  7. export default new Router({
  8. mode: 'history',
  9. routes: [
  10. {
  11. path: '/login', //登录页
  12. name: 'Login',
  13. component: Login
  14. },
  15. {
  16. path: '/', //首页
  17. name: 'Main',
  18. component: Main,
  19. meta: {
  20. requireAuth: true, // 添加该字段,表示进入这个路由是需要登录的
  21. },
  22. },
  23. { path: '*', component: P404 } //这里是保证错误地址会跳转到404界面进行提示
  24. ]
  25. })

这些方法的编写顺序可能没有体现出来,不过最终效果就是这个了,如果有疑问欢迎留言

将会尽快回复您

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值