您好,登錄后才能下訂單哦!
小編給大家分享一下vue+vuex+axios如何實現登錄、注冊頁權限攔截,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
實現過程:
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"> <h4 class="title">登錄</h4> <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" :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是一套用于構建用戶界面的漸進式JavaScript框架,Vue與其它大型框架的區別是,使用Vue可以自底向上逐層應用,其核心庫只關注視圖層,方便與第三方庫和項目整合,且使用Vue可以采用單文件組件和Vue生態系統支持的庫開發復雜的單頁應用。
看完了這篇文章,相信你對“vue+vuex+axios如何實現登錄、注冊頁權限攔截”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。