VUE 项目集成Vuex,实现简单用户登入页面登入权限认证
第一步:VUE 项目安装Vuex 模块
打开cmd 窗口指令,切换至VUE 项目所在路径地址,执行如下指令:
cnpm install vuex --save
在 VUE项目src 文件夹下新建一个文件夹 store,并在该目录下新建 index.js 文件,在该文件中引入 vue 和 vuex,代码如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
index.js 模块核心功能描述:设置用户是否登入的状态值和获取用户是否登入状态值。核心代码如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = 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))
}
}
})
export default store
第二步:修改路由配置:
修改一下 src\router\index.js,
在需要拦截的路由中加一条元数据,设置一个 requireAuth
字段如下:
{
path: '/index',
name: 'AppIndex',
component: AppIndex,
meta: {
requireAuth: true
}
}
完整代码:src\router\index.js
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
// 导入刚才编写的组件
import AppIndex from '@/components/home/AppIndex'
import Login from '@/components/Login'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
// 下面都是固定的写法
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/index',
name: 'AppIndex',
component: AppIndex,
meta: {
requireAuth: true
}
}
]
})
第三步:钩子函数判断路径是否拦截请求地址
钩子函数:在某些时候会被调用的函数。我们这里使用 router.beforeEach() = 在访问每一个路由前调用
打开 src\main.js
,首先添加对 store
的引用
// 引入vuex
import store from './store'
修改 Vue 对象里的内容
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
编写router.beforeEach() 函数:
/* 钩子函数:判断访问的路径是否需要登入*/
router.beforeEach((to, from, next) => {
if (to.meta.requireAuth) {
if (store.state.user.username) {
next()
} else {
next({
path: 'login',
query: {redirect: to.fullPath}
})
}
} else {
next()
}
}
)
功能说明:首先判断访问的路径是否需要登录,如果需要,判断 store
里有没有存储 user
的信息,如果存在,则放行,否则跳转到登录页面,并存储访问的页面路径(以便在登录后跳转到访问页)
完整main.js 代码:
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
// 引入vuex
import store from './store'
// 引入ElementUI
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// 设置反向代理,前端请求默认发送到 http://localhost:8443/api
var axios = require('axios')
axios.defaults.baseURL = 'http://localhost:7080/api'
// 全局注册,之后可在其他组件中通过 this.$axios 发送数据
Vue.prototype.$axios = axios
Vue.config.productionTip = false
Vue.use(ElementUI)
/* eslint-disable no-new */
/* 钩子函数:判断访问的路径是否需要登入*/
router.beforeEach((to, from, next) => {
if (to.meta.requireAuth) {
if (store.state.user.username) {
next()
} else {
next({
path: 'login',
query: {redirect: to.fullPath}
})
}
} else {
next()
}
}
)
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
第四步:修改Login.vue 组件
业务逻辑描述:
1、用户输入用户名和密码点击登入,向后端发送相关数据。
2、等待后端返回成功时,触发 store
中的 login()
方法,把 loginForm
对象传递给 store
中的 use
r 对象。
3、获取登录前页面的路径并跳转,如果该路径不存在,则跳转到首页
核心代码:
<template>
<body id="poster">
<el-form class="login-container" label-position="left"
label-width="0px">
<h3 class="login_title">系统登录</h3>
<el-form-item>
<el-input type="text" v-model="loginForm.username"
auto-complete="off" placeholder="账号"></el-input>
</el-form-item>
<el-form-item>
<el-input type="password" v-model="loginForm.password"
auto-complete="off" placeholder="密码"></el-input>
</el-form-item>
<el-form-item style="width: 100%">
<el-button type="primary" style="width: 100%;background: #505458;border: none" v-on:click="login">登录</el-button>
</el-form-item>
</el-form>
</body>
</template>
<script>
export default {
name: "Login",
data () {
return {
loginForm: {
username: '',
password: ''
},
responseResult: []
}
},
methods: {
login () {
var _this = this
console.log(this.$store.state)
this.$axios
.post('/login', {
username: this.loginForm.username,
password: this.loginForm.password
})
.then(successResponse => {
if (successResponse.data.code === 200) {
// store 值存储
_this.$store.commit('login', _this.loginForm)
var path = this.$route.query.redirect
this.$router.replace({path: path === '/' || path === undefined ? '/index' : path})
}
})
.catch(failResponse => {
})
}
}
}
</script>
<style scoped>
#poster {
background-position: center;
height: 100%;
width: 100%;
background-size: cover;
position: fixed;
}
body{
margin: 0px;
}
.login-container {
border-radius: 15px;
background-clip: padding-box;
margin: 90px auto;
width: 350px;
padding: 35px 35px 15px 35px;
background: #fff;
border: 1px solid #eaeaea;
box-shadow: 0 0 25px #cac6c6;
}
.login_title {
margin: 0px auto 40px auto;
text-align: center;
color: #505458;
}
</style>
SpringBoot 后端代码添加如下功能:
1、创建登入拦截器:实现访问请求地址拦截,判断是不是需要进行拦截的请求的地址:
package com.zzg.wj.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import com.zzg.wj.domain.AuthUser;
/**
* 登入拦截器
* @author Administrator
*
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
String contextPath=session.getServletContext().getContextPath();
String[] requireAuthPages = new String[]{
"index",
};
String uri = request.getRequestURI();
// 指定字符串移除指定字符
uri = StringUtils.remove(uri, contextPath+"/");
String page = uri;
if(begingWith(page, requireAuthPages)){
AuthUser user = (AuthUser) session.getAttribute("user");
if(user==null) {
// 重定向登入页面
response.sendRedirect("login");
return false;
}
}
return true;
}
// 判断请求路径是否为需要权限
private boolean begingWith(String page, String[] requiredAuthPages) {
boolean result = false;
for (String requiredAuthPage : requiredAuthPages) {
if(StringUtils.startsWith(page, requiredAuthPage)) {
result = true;
break;
}
}
return result;
}
}
2、Web 配置类:配置cors 和注册拦截器
package com.zzg.wj.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.zzg.wj.interceptor.LoginInterceptor;
/**
* cros 跨域问题
* @author Administrator
*
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
.maxAge(3600);
}
@Bean
public LoginInterceptor getLoginIntercepter() {
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry){
registry.addInterceptor(getLoginIntercepter()).addPathPatterns("/**");
}
}
效果演示:
运行前后端项目,访问 http://localhost:8080/index ,发现页面直接跳转到了 http://localhost:8080/login?redirect=%2Findex
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。