模块技术点
封装API
登录
<template>
<div>
<el-dialog title="登录" :visible.sync="uplogin" width="30%">
<el-form :model="loginForm" status-icon :rules="rules" ref="enrollForm">
<!-- 注册用户名 -->
<el-form-item prop="userName">
<el-input
type="text"
v-model="loginForm.userName"
placeholder="请输入用户名"
autocomplete="off"
style="width: 300px"
>
<i slot="prefix" class="el-icon-s-custom"></i>
</el-input>
</el-form-item>
<!-- 密码 -->
<el-form-item prop="password">
<el-input
type="password"
v-model="loginForm.password"
placeholder="请输入密码"
autocomplete="off"
style="width: 300px"
>
<i slot="prefix" class="el-icon-view"></i>
</el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" style="width: 100%" @click="toLogin('enrollForm')">登录</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import API from "@/api/login.js";
export default {
name: "Login",
props: ["loginDialog"],
components: {},
data() {
return {
//!登录弹出
uplogin: false,
// 登录
loginForm: {
userName: "",
password: ""
},
rules: {
userName: [
{ required: true, message: "请输入用户名称", trigger: "blur" }
],
password: [, { required: true, message: "请输入密码", trigger: "blur" }]
}
};
},
mounted() {},
methods: {
// 登录
toLogin(formName) {
this.$refs[formName].validate(valid => {
if (valid) {
API.login(this.loginForm).then(res => {
// console.log(res);
// 把登录接口请求到的数据赋值给users
let users = res.user;
this.$store.commit('addLogin',users);
if (res.code == "001") {
this.$notify({
title: "成功",
message: res.msg,
type: "success"
});
// 登录成功关闭登录弹框
this.uplogin = false;
} else {
this.$notify({
title: "失败",
message: res.msg,
type: "error"
});
}
})
} else {
return false;
}
});
}
},
watch: {
// 监听登录状态
loginDialog(value){
if(value == true){
this.uplogin = value;
this.$emit("flag");
}
}
}
};
</script>
<style scoped>
</style>
登录鉴权 路由守卫
// 全局路由守卫
router.beforeEach((to, from, next) => {
if(to.path == "/collection" || to.path == "/cart" || to.path == "/order"){
if(store.state.userName == ""){
next("/homePage");
}
}
next();
})
全局组件
// 在main.js中
// 注册全局组件登录
import Login from "./components/Break/login.vue"
Vue.component(Login.name, Login);
全局变量
// 在main.js中
// 全局变量
Vue.prototype.$target = "http://39.100.7.70:81/";
整体项目中的难点
登录鉴权先判断用户名是否存储在Vuex中
根据Vuex中是否有数据来判断用户是否登录
如果Vuex中没有数据就代表用户没有登录,需要弹出登录的弹框
如果Vuex中有数据就代表用户已经登录就可以直接进行下面的操作
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import VuexPersistence from 'vuex-persist'
const vuexLocal = new VuexPersistence({
storage: window.localStorage,
key: "QJYX"
})
export default new Vuex.Store({
state: {
// 登录的名字
userName: "",
// 登录的id
user_id: ""
},
mutations: {
// 登录
addLogin(state, user) {
state.userName = user.userName;
state.user_id = user.user_id;
// router.push('/my');
}
},
plugins: [vuexLocal.plugin]
})