欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue+vuex+axios实现登录、注册页权限拦截

程序员文章站 2024-01-20 08:36:04
在github上有很多写好的模板,这个项目也是基于模板做的。 现在记录一下我做的过程 1、修改config文件夹里的dev.env.js里的base_api,把地址改成...

在github上有很多写好的模板,这个项目也是基于模板做的。

现在记录一下我做的过程

1、修改config文件夹里的dev.env.js里的base_api,把地址改成请求后端的公共部分

base_api: '"http://192.168.xx.xx"', 

2、接下来就是操作src文件,先在 views里写好vew组件(login.vue,regist.vue),写好到router里的index.js里配置好路径

login.vue

<template>
 <div class="login-container">
  <el-form autocomplete="on" :model="loginform" :rules="loginrules" ref="loginform" label-position="left"
     label-width="0px"
     class="card-box login-form">
   <h3 class="title">登录</h3>
   <el-form-item prop="name">
  <span class="svg-container svg-container_login">
   <svg-icon icon-class="user"/>
  </span>
    <el-input name="name" disabled type="text" v-model="loginform.name" autocomplete="on"
      placeholder="用户名"/>
   </el-form-item>
   <el-form-item prop="password">
  <span class="svg-container">
   <svg-icon icon-class="password"></svg-icon>
  </span>
    <el-input name="password" :type="pwdtype" @keyup.enter.native="handlelogin" v-model="loginform.password"
      autocomplete="on"
      placeholder="密码"></el-input>
    <span class="show-pwd" @click="showpwd"><svg-icon icon-class="eye"/></span>
   </el-form-item>
   <el-form-item>
    <el-button type="primary" style="width:100%;" :loading="loading" @click.native.prevent="handlelogin">
    登录
    </el-button>
   </el-form-item>
  </el-form>
  </div>
</template>
<script>
 export default {
 name: 'login',
 data() {
  const validateusername = (rule, value, callback) => {
  if (value.trim().length<1) {
   callback(new error('用户名不能为空'))
  } else {
   callback()
  }
  };
  const validatepass = (rule, value, callback) => {
  if (value.trim().length < 1) {
   callback(new error('密码不能为空'))
  } else {
   callback()
  }
  };
  return {
  loginform: {
   name: '',
   password: ''
  },
  loginrules: {
   name: [{required: true, trigger: 'blur', validator: validateusername}],
   password: [{required: true, trigger: 'blur', validator: validatepass}]
  },
  loading: false,
  pwdtype: 'password'
  }
 },
 methods: {
  showpwd() {
  if (this.pwdtype === 'password') {
   this.pwdtype = ''
  } else {
   this.pwdtype = 'password'
  }
  },
  handlelogin() {
  this.$refs.loginform.validate(valid => {
   if (valid) {
   this.loading = true;
   this.$store.dispatch('login', this.loginform).then(() => {
    this.loading = false;
    this.$router.push({path: '/'});
   }).catch((e) => {
    this.loading = false
   })
   } else {
   console.log('error submit!!')
   return false
   }
  })
  }
 }
 }
</script>

router/index.js

{ path: '/login', component: _import('login/login'), hidden: true } 

3、在api里的login.js里写好与后端对接的接口地址,在stores里的modules里的user.js里定义user,有state,mutations,action,具体的请求操作写在action里,login.vue或regist.vue调用user.js里写好的请求,getter.js里定义store的getters

api/login.js

import request from '@/utils/request'
export function login(name,password) {
 return request({
 url: '/xx/xx',
 method: 'post',
 data: {
  name,
  password
 } 
 })
}

stores/modules/user.js

  import { login,regist,logout } from '@/api/login'
  import { gettoken,settoken } from '@/utils/auth'
  const user = {
  state: {
   name:'',
   token:''
  },
  mutations: {
   set_name: (state, name) => {
   state.name = name;
   },
   set_token: (state, token) => {
   state.token = token;
   settoken(token);
   }
  },
  actions: {
   // 登录
   login({ commit }, userinfo) {
   const name = userinfo.name.trim();
   const password = userinfo.password.trim();
   return new promise((resolve, reject) => {
    login(name, password).then(response => {
    const data = response.data;
    commit('set_name', data.name);
    commit('set_token', data.token);
    setname(data.name);
    settoken(data.token);
    resolve(response); }).catch(error => { reject(error) }) }) },
   // 注册 
   regist({ commit }, userinfo) { 
   const name= userinfo.name.trim(); 
   const password = userinfo.password.trim(); 
   return new promise((resolve, reject) => { 
    regist(name, password).then(response => { 
    const data = response.data; 
    commit('set_name', data.name); 
    commit('set_token', data.token);
    setname(data.name);settoken(data.token); 
    resolve(response);
    }).catch(error => { 
    reject(error) }) }) }, 
   // 登出 
   logout({ commit, state }) {
   return new promise((resolve, reject) => {
   logout().then(response => {
    commit('set_name', '');
    commit('set_token', '');
    setname('');
    settoken(false);
    //removename();
    //removetoken();
    resolve(response);
   }).catch(error => {
    reject(error)
   })
   })
  }, 
   // 前端 登出 
   fedlogout({ commit }) { 
   return new promise(resolve => {
  settoken(false);
 commit('set_token', false);
 resolve()
   })
   }
  }
  }
  export default user

getter.js:

const getters={
 name:state=>state.user.name,
 token:state=>state.user.token
}
export default getter

4、在utils里的auth.js里对cookies进行操作,写入,读取,删除用户权限,是否登录的标志等

import cookies from 'js-cookies'
export function setname(name) {
 return cookies.set("name", name);
}
export function getname() {
 return cookies.get("name");
}
export function settoken(token) {
 return cookies.set("token", token);
}
export function gettoken() {
 return cookies.get("token");
}

5、在permission.js里写白名单,对白名单以外的跳转进行拦截然后跳转登录,同时判断用户权限,是否登录,等

import router from './router'
import store from './store'
import nprogress from 'nprogress' // progress 进度条
import 'nprogress/nprogress.css'// progress 进度条样式
import {message} from 'element-ui'
import {getname, gettoken} from "@/utils/auth"; // 验权
const whitelist = ['/login', '/regist']; // 不重定向白名单
router.beforeeach((to, from, next) => {
 nprogress.start();
 if (whitelist.indexof(to.path) !== -1) {
 next();
 } else {
 if (gettoken()==="true") {
  next();
  nprogress.done()
 } else {
  next({path: '/login'});
  nprogress.done()
 }
 }
})
router.aftereach(() => {
 nprogress.done() // 结束progress
})

6、utils里的request.js里写拦截码,对后端返回的特定码进行拦截然后做相应的操作

import axios from 'axios'
import { message, messagebox } from 'element-ui'
import store from '../store'
// 创建axios实例
const service = axios.create({
 baseurl: process.env.base_api, // api的base_url
 timeout: 15000     // 请求超时时间
});
// respone拦截器
service.interceptors.response.use(
 response => {
 /**
 * code为非200是抛错 可结合自己业务进行修改
 */
 const res = response.data;
 //const res = response;
 if (res.code !== '200' && res.code !== 200) {
  if (res.code === '4001' || res.code === 4001) {
  messagebox.confirm('用户名或密码错误,请重新登录', '重新登录', {
   confirmbuttontext: '重新登录',
   cancelbuttontext: '取消',
   type: 'warning'
  }).then(() => {
   store.dispatch('fedlogout').then(() => {
    location.reload()// 为了重新实例化vue-router对象 避免bug
   })
  })
  }
  if (res.code === '4009' || res.code === 4009) {
  messagebox.confirm('该用户名已存在,请重新注册!', '重新注册', {
   confirmbuttontext: '重新注册',
   cancelbuttontext: '取消',
   type: 'warning'
  }).then(() => {
   store.dispatch('fedlogout').then(() => {
   location.reload()// 为了重新实例化vue-router对象 避免bug
   })
  })
  }
  return promise.reject('error')
 } else {
  return response.data
 }
 },
 error => {
 message({
  message: error.message,
  type: 'error',
  duration: 5 * 1000
 });
 return promise.reject(error)
 }
)
export default service

以上就是登录注册的核心部分,写的不对的地方请指教

这篇vue+vuex+axios实现登录、注册页权限拦截就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。