vue通过vue-router拦截实现登录验证
在实际开发中,有些页面需要登录之后才能访问,采用vue-router+vuex+elememt-ui+axios的方式实现。以下是案列代码:login.vue<template><div class="login"><el-input type="text" v-model="u
·
在实际开发中,有些页面需要登录之后才能访问,采用vue-router+vuex+elememt-ui+axios的方式实现。
以下是案列代码:
login.vue
<template>
<div class="login">
<el-input type="text" v-model="username" placeholder="请输入用户名"></el-input>
<el-input type="password" v-model="userpsd" placeholder="请输入密码"></el-input>
<el-button type="primary" @click="toLogin">登录</el-button>
</div>
</template>
<script>
import {mapActions,mapState} from 'vuex'
export default {
name: 'login',
props: [''],
data() {
return {
username: "",
userpsd: "",
};
},
computed: {
...mapState(["userinfo", "isLogin"])
},
mounted() {
console.log(this.$route.params.path);
},
methods: {
...mapActions(["getUserInfo"]),
toLogin() {
if (this.username == "") {//自行验证用户名规则
return;
} else if (this.userpsd == "") {//自行验证密码规则
return;
} else {
let data = {};
data.username = this.username;
data.password = this.userpsd;
this.getUserInfo(data).then(() => {
if (this.isLogin) {
//若是使用用户信息,则本地保存用户信息,根据需求自行使用本地保存方式
sessionStorage.setItem("userinfo", JSON.stringify(this.userinfo));
//是否登录的标志位
sessionStorage.setItem("isLogin", true);
//登录成功后返回访问的页面
this.$router.push({
path: this.$route.params.path
});
} else {//登录未成功to do sth
sessionStorage.setItem("userinfo", '');
sessionStorage.setItem("isLogin", '');
}
})
.catch(err => {
console.log(err);
});
}
},
}
}
</script>
<style lang='' scoped>
.login .el-input {
margin: .5rem 0;
}
.login .el-button--primary {
width: 100%;
margin: .5rem 0;
}
</style>
router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/index'
const home = r => require.ensure([], () => r(require('@/components/home')), 'home');
const personCenter= r => require.ensure([], () => r(require('@/components/personCenter')), 'personCenter');
const login = r => require.ensure([], () => r(require('@/components/login')), 'login');
const notFound = r => require.ensure([], () => r(require('@/components/notFound')), 'notFound');
Vue.use(Router);
const router = new VueRouter({
routes: [{
path: '/home',
name: 'home',
component: home
},
{
path: '/personCenter',
name: 'personCenter',
component: personCenter,
meta: {
need2Login: true
}
},
{
path: '/login',
name: 'login',
component: login,
},
{
path: "/404",
name: "notFound",
component: notFound
},
{
path: "*", // 此处需特别注意置于最底部
redirect: "/404"
},
]
})
router.beforeEach((to, from, next) => { //全局钩子函数
to.matched.some((route) => {
// to.matched.forEach((route) => {
if (route.meta.need2Login) { //通过此操作可以判断哪些页面需要登录
if (store.state.isLogin || sessionStorage.getItem('isLogin')) {
next()
} else {
next({ name: 'login', params: { path: route.path } })
}
} else {
next();
}
});
});
export default router;
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './action'
Vue.use(Vuex);
const state = {
userinfo: {}, //登录信息
isLogin: '', //是否已登录
}
export default new Vuex.Store({
state,
actions,
mutations,
})
store/mutation-types.js
export const GETUSERINFO = 'GETUSERINFO'
store/action.js
import {login} from '@/service/api'
export default {
async getUserInfo({ state, commit }, payload) {
let res = await login(payload);
if (res.result.code === 10000) {//登录成功dispatch
commit('GETUSERINFO', { info: res.data, isLogin: true })
} else {
commit('GETUSERINFO', { info: res, isLogin: false })
}
}
}
store/mutations.js
import { GETUSERINFO } from './mutation-types'
export default {
[GETUSERINFO](state, { info, isLogin }) {
state.userinfo = info;
state.isLogin = isLogin;
}
}
service/api.js
import ajax from './apiConfig';
export const login = (data) => {
return ajax.post('/app/login', data)
}
service/apiConfig.js
import axios from 'axios';
import qs from 'qs';
// 设置 POST 请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 在向服务器发送前,修改请求数据(只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法)
axios.defaults.transformRequest = [(data) => { return qs.stringify(data) }]
// 在传递给 then/catch 前,允许修改响应数据
// axios.defaults.transformResponse = [(data) => { return JSON.parse(data) }]
// 配置 CORS 跨域
// 表示跨域请求时是否需要使用凭证
axios.defaults.withCredentials = true;
axios.defaults.crossDomain = true;
// 设置超时
axios.defaults.timeout = 40000;
// 拦截器的说明
// 1、interceptor必须在请求前设置才有效。
// 2、直接为axios全局对象创建interceptor, 会导致全局的axios发出的请求或接收的响应都会被拦截到, 所以应该使用axios.create() 来创建单独的axios实例。
//设置地址
const baseUrl='';
// 创建axios实例
let instance = axios.create({
baseURL: baseUrl
})
// Add a request interceptor
instance.interceptors.request.use(function(config) {
return config;
}, function(error) {
return Promise.reject(error);
});
// Add a response interceptor
instance.interceptors.response.use(function(response) {
// Do something with response data
return response.data;
}, function(error) {
// Do something with response error
return Promise.reject(error);
});
export { instance };
更多推荐
已为社区贡献6条内容
所有评论(0)