在实际开发中,有些页面需要登录之后才能访问,采用vue-router+vuex+elememt-ui+axios的方式实现。
以下是案列代码:
login.vue
登录
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 };