首页 >web前端 >js教程 >通过利用vue+vuex+axios这几种技术实现登录、注册页权限拦截(详细教程)

通过利用vue+vuex+axios这几种技术实现登录、注册页权限拦截(详细教程)

亚连
亚连原创
2018-05-31 15:56:374194浏览

下面我就为大家分享一篇vue+vuex+axios实现登录、注册页权限拦截,具有很好的参考价值,希望对大家有所帮助。

在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>
 <p 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>
  </p>
</template>
<script>
 export default {
 name: &#39;login&#39;,
 data() {
  const validateUsername = (rule, value, callback) => {
  if (value.trim().length<1) {
   callback(new Error(&#39;用户名不能为空&#39;))
  } else {
   callback()
  }
  };
  const validatePass = (rule, value, callback) => {
  if (value.trim().length < 1) {
   callback(new Error(&#39;密码不能为空&#39;))
  } else {
   callback()
  }
  };
  return {
  loginForm: {
   name: &#39;&#39;,
   password: &#39;&#39;
  },
  loginRules: {
   name: [{required: true, trigger: &#39;blur&#39;, validator: validateUsername}],
   password: [{required: true, trigger: &#39;blur&#39;, validator: validatePass}]
  },
  loading: false,
  pwdType: &#39;password&#39;
  }
 },
 methods: {
  showPwd() {
  if (this.pwdType === &#39;password&#39;) {
   this.pwdType = &#39;&#39;
  } else {
   this.pwdType = &#39;password&#39;
  }
  },
  handleLogin() {
  this.$refs.loginForm.validate(valid => {
   if (valid) {
   this.loading = true;
   this.$store.dispatch(&#39;Login&#39;, this.loginForm).then(() => {
    this.loading = false;
    this.$router.push({path: &#39;/&#39;});
   }).catch((e) => {
    this.loading = false
   })
   } else {
   console.log(&#39;error submit!!&#39;)
   return false
   }
  })
  }
 }
 }
</script>

router/index.js

{ path: &#39;/login&#39;, component: _import(&#39;Login/login&#39;), 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 &#39;@/utils/request&#39;
export function login(name,password) {
 return request({
 url: &#39;/XX/XX&#39;,
 method: &#39;post&#39;,
 data: {
  name,
  password
 } 
 })
}

stores/modules/user.js

  import { login,regist,logout } from &#39;@/api/login&#39;
  import { getToken,setToken } from &#39;@/utils/auth&#39;
  const user = {
  state: {
   name:&#39;&#39;,
   token:&#39;&#39;
  },
  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(&#39;SET_NAME&#39;, data.name);
    commit(&#39;SET_TOKEN&#39;, 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(&#39;SET_NAME&#39;, data.name); 
    commit(&#39;SET_TOKEN&#39;, 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(&#39;SET_NAME&#39;, &#39;&#39;);
    commit(&#39;SET_TOKEN&#39;, &#39;&#39;);
    setName(&#39;&#39;);
    setToken(false);
    //removeName();
    //removeToken();
    resolve(response);
   }).catch(error => {
    reject(error)
   })
   })
  }, 
   // 前端 登出 
   FedLogOut({ commit }) { 
   return new Promise(resolve => {
  setToken(false);
 commit(&#39;SET_TOKEN&#39;, 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 &#39;js-cookies&#39;
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 &#39;./router&#39;
import store from &#39;./store&#39;
import NProgress from &#39;nprogress&#39; // Progress 进度条
import &#39;nprogress/nprogress.css&#39;// Progress 进度条样式
import {Message} from &#39;element-ui&#39;
import {getName, getToken} from "@/utils/auth"; // 验权
const whiteList = [&#39;/login&#39;, &#39;/regist&#39;]; // 不重定向白名单
router.beforeEach((to, from, next) => {
 NProgress.start();
 if (whiteList.indexOf(to.path) !== -1) {
 next();
 } else {
 if (getToken()==="true") {
  next();
  NProgress.done()
 } else {
  next({path: &#39;/login&#39;});
  NProgress.done()
 }
 }
})
router.afterEach(() => {
 NProgress.done() // 结束Progress
})

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

import axios from &#39;axios&#39;
import { Message, MessageBox } from &#39;element-ui&#39;
import store from &#39;../store&#39;
// 创建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 !== &#39;200&#39; && res.code !== 200) {
  if (res.code === &#39;4001&#39; || res.code === 4001) {
  MessageBox.confirm(&#39;用户名或密码错误,请重新登录&#39;, &#39;重新登录&#39;, {
   confirmButtonText: &#39;重新登录&#39;,
   cancelButtonText: &#39;取消&#39;,
   type: &#39;warning&#39;
  }).then(() => {
   store.dispatch(&#39;FedLogOut&#39;).then(() => {
    location.reload()// 为了重新实例化vue-router对象 避免bug
   })
  })
  }
  if (res.code === &#39;4009&#39; || res.code === 4009) {
  MessageBox.confirm(&#39;该用户名已存在,请重新注册!&#39;, &#39;重新注册&#39;, {
   confirmButtonText: &#39;重新注册&#39;,
   cancelButtonText: &#39;取消&#39;,
   type: &#39;warning&#39;
  }).then(() => {
   store.dispatch(&#39;FedLogOut&#39;).then(() => {
   location.reload()// 为了重新实例化vue-router对象 避免bug
   })
  })
  }
  return Promise.reject(&#39;error&#39;)
 } else {
  return response.data
 }
 },
 error => {
 Message({
  message: error.message,
  type: &#39;error&#39;,
  duration: 5 * 1000
 });
 return Promise.reject(error)
 }
)
export default service

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

红黑树的插入详解及Javascript实现方法示例

js+canvas实现滑动拼图验证码功能

JS从非数组对象转数组的方法小结

以上是通过利用vue+vuex+axios这几种技术实现登录、注册页权限拦截(详细教程)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn