配置store
import Vue from 'vue'
import Vuex from 'vuex'
//相当于java里面创建实体类
Vue.use(Vuex);
export default new Vuex.Store({
//状态
state: {
//从localStorage里面获取值
userinfo: JSON.parse(localStorage.getItem("userinfo "))
// userinfo: localStorage.getItem("userinfo ")
},
mutations: {
//从一些方法里面创建axios中获取数据放进这个变量里面,如果是对象的话要转换json
SET_USERINFO: (state, userinfo) => {
state.userinfo = userinfo;
localStorage.setItem("userinfo ", JSON.stringify(userinfo));
}
},
//创建get方法 让其他方法获得state状态,这个状态里面拥有数据
getters: {
getUser: state => {
return state.userinfo;
}
},
// actions: {},
// modules: {}
});
然后需要在main.js里面注册
new Vue({
render: h => h(App), //跳到视图的展示vue
// 主函数调用路由
router,
store,
}).$mount('#app')
//=== el:"#app",也就是挂载到id为app的标签里面
配置页面,进行后端存值
<template>
<el-form
:model="user"
:rules="rules"
ref="user"
label-width="100px"
class="logintest-ruleForm"
>
<el-form-item label="账号" prop="name">
<el-input v-model="user.name"></el-input>
</el-form-item>
<el-form-item label="密码" prop="password">
<el-input v-model="user.password" type="password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('user')"
>登录
</el-button
>
<el-button @click="resetForm('user')">重置</el-button>
</el-form-item>
</el-form>
</template>
<script>
export default {
name: "loginTest",
data() {
return {
user: {
name: '',
password: '',
},
rules: {
name: [
{required: true, message: '请输入账号', trigger: 'blur'},
{
min: 3,
max: 5,
message: '长度在 3 到 5 个字符',
trigger: 'blur',
},
],
password: [
{required: true, message: '请输入密码', trigger: 'blur'},
{
min: 3,
max: 5,
message: '长度在 3 到 5 个字符',
trigger: 'blur',
},
],
},
}
},
methods: {
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
// alert('submit!')
this.$axios.post('/mybatis_plus/user/getUser', this.user).then(response => {
//把返回的值放进store里面
this.$store.commit("SET_USERINFO", response.data)
alert(response.data)
alert(response.data.name)
alert(response.data.password)
// if (response.data.eq('fail')){
// this.$router.replace("/loginTest")
// }
this.$router.replace("/index")
}
)
// 业务逻辑 登录业务,向后端请求端口
} else {
return false
}
})
},
resetForm(formName) {
this.$refs[formName].resetFields()
},
}
}
</script>
<style scoped>
.logintest-ruleForm {
margin: auto;
width: 40%;
/*border: 3px solid green;*/
padding: 10px;
}
</style>
进行前端取值,把值放进usesrinfo里面,因为只是存一个值,所以收到的是一个对象的json。
data() {
return {
userinfo: '',
}
},
methods: {
getUser() {
this.userinfo = this.$store.getters.getUser;
}
},
created() {
this.getUser();
}