前端登录拦截器的简单设置。

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

1.Vuex的引入

Vuex 是什么?

如果创建vue 项目时没有引入vuex ,运行 npm install vuex --save,之后,在 src 目录下新建一个文件夹 store,并在该目录下新建 index.js 文件,在该文件中引入 vue 和 vuex

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

index.js文件中设置我们需要的状态变量和方法。

实现前端拦截器,需要一个记录用户信息的变量,创建一个user对象

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state: {
user: {
username: window.localStorage.getItem('user' || '[]') == null ? '' : JSON.parse(window.localStorage.getItem('user' || '[]')).username
}
},
mutations: {
login (state, user) {
state.user = user
window.localStorage.setItem('user', JSON.stringify(user))
}
},
actions: {
},
modules: {
}
})

localStorage,为本地存储

mutations中设置一个储存用户方法

2.修改路由配置

修改 src\router\index.js,在需要拦截的路由中加一条元数据,设置一个 requireAuth 字段

例如

{
path: '/books/:bid',
component: ForeLayout,
children: [{
path: '',
component: () => import('@/foreviews/bookdetails/index'),
meta: {
requireAuth: true
}
}]
},

3.使用钩子函数判断是否拦截

使用 router.beforeEach(),意思是在访问每一个路由前调用。

打开 src\main.js ,添加对 store 的引用

import store from './store'

new Vue()中添加store

接着写 beforeEach() 函数

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/en' // lang i18n

// 设置反向代理,前端请求默认发送到 http://localhost:8443/api
var axios = require('axios')
axios.defaults.baseURL = 'http://localhost:8443/api'
// 全局注册,之后可在其他组件中通过 this.$axios 发送数据
Vue.prototype.$axios = axios

Vue.config.productionTip = false

Vue.use(ElementUI, { locale })

router.beforeEach((to, from, next) => {
if (to.meta.requireAuth) {
if (store.state.user.username) {
next()
} else {
next({
path: 'toLogin',
query: { redirect: to.fullPath }
})
}
} else {
next()
}
}
)

new Vue({
el: '#app',
router,
store,
render: h => h(App)
}).$mount('#app')

在登录的axios的登录方法中调用方法

1.点击登录按钮,向后端发送数据
2.受到后端返回的成功代码时,触发 store 中的 login() 方法,把 loginForm 对象传递给 store 中的 user 对象
3.获取登录前页面的路径并跳转,如果该路径不存在,则跳转到首页

submitForm (formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
var _this = this
this.$axios.post('/login', {
userName: this.loginForm.name,
password: this.loginForm.pass
})
.then(response => {
// 登录成功
if (response.data.code === 400) {
this.$notify({
title: '成功',
message: response.data.msg,
type: 'success'
})
_this.$store.commit('login', _this.loginForm)

var path = this.$route.query.redirect

this.$router.replace({ path: path === '/' || path === undefined ? '/index' : path })
}

// 登录失败
if (response.data.code === '401' || response.data.code === '402') {
this.$notify.error({
title: '错误',
message: response.data.msg
})
}
})
.catch(failRespose => {

})
} else {
console.log('error submit!!')
return false
}
})
},