一、vuex使用来干啥的
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库,可以理解为存放公用变量和公用方法的地方,但是不开发大型单页应用,使用 Vuex 可能是冗余的。
二、vuex安装
npm install vuex@next --save
三、vuex的结构
可以新建一个store文件夹,来存放vuex相关代码,把它当成一个公共仓库
一个简单的vuex代码如下:
import { createApp } from 'vue'
import { createStore } from 'vuex'
const store = createStore({
state () {
return {
count: 0
}
},
mutations: {
increment (state) {
state.count++
}
}
})
const app = createApp({ /* 根组件 */ })
app.use(store)
四、获取和改变vuex的状态和方法
获取状态:this.$store.state.变量名称
调用方法: this.$store.commit('方法名称',变量);
五、vuex中的modules
把一个store大仓库,分成若干个modules小仓库,便于管理。 实例:
import Vue from 'vue'
import Vuex from 'vuex'
import user from "./module/user.js"
import vuexPersistedstate from "vuex-persistedstate"
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
user,
},
plugins: [
vuexPersistedstate({
key: "use",
storage: window.localStorage
})]
})
六、action
action类似于mutation,但是Action 提交的是 mutation,而不是直接变更状态
其中的context就类似于mini版的store
export default {
state: {
userInfor: {},
},
getters: { },
mutations: {
//同步方法
getuserInfor(state, value) {
state.userInfor = value
}
},
actions: {
//异步调用同步方法
getuserInforAsync(context, value) {
context.commit('getuserInfor', value)
}
},
namespaced: true,//命名空间
}
七、mapState辅助函数
当需要获取多个state时,可以用mapState来一次性获取再从中[解构],这样可以减少声明的重复和冗余
举个登录的例子
//src/views/LoginView.vue
<template>
<div class="polpe">
<div class="login">
<h2>登录</h2>
<a-form id="components-form-demo-normal-login" :form="form" class="login-form" @submit="handleSubmit">
<a-form-item>
<a-input v-decorator="[
'account',
{ rules: [{ required: true, message: '请输入用户名!' }] },
]" placeholder="请输入用户名">
<a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
</a-input>
</a-form-item>
<a-form-item>
<a-input v-decorator="[
'pwd',
{ rules: [{ required: true, message: '请输入密码!' }] },
]" type="password" placeholder="请输入密码">
<a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
</a-input>
</a-form-item>
<a-form-item>
<a-input v-decorator="[
'imgcode',
{ rules: [{ required: true, message: '请输入验证码!' }] },
]" placeholder="请输入验证码">
<a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
</a-input>
<img :src="imgCode"
@click="() => { imgCode = 'http://47.93.101.203/adminapi/captcha_pro?' + new Date() }" alt="">
</a-form-item>
<a-form-item>
<a-checkbox v-decorator="[
'remember',
{
valuePropName: 'checked',
initialValue: false,
},
]">
记住密码
</a-checkbox>
<a-button type="primary" html-type="submit" class="login-form-button">
Log in
</a-button>
</a-form-item>
</a-form>
</div>
</div>
</template>
<script>
import { mapActions, mapState } from 'vuex';
import { getLogin } from '@/api'
export default {
props: {},
components: {},
data() {
return {
imgCode: 'http://47.93.101.203/adminapi/captcha_pro?' + new Date()
};
},
computed: {
...mapState('user', ['userInfor'])
},
watch: {},
created() {},
mounted() {},
beforeCreate() {
this.form = this.$form.createForm(this, { name: 'normal_login' });
},
methods: {
...mapActions('user', ['getuserInforAsync']),
handleSubmit(e) {
e.preventDefault();
this.form.validateFields((err, values) => {
if (!err) {
getLogin(values).then(res => {
if (res.status === 200) {
this.getuserInforAsync(res)//对登录信息进行存储
this.$message.success('登录成功', 1)
localStorage.setItem('token', res.data.token)
if (values.remember) {
localStorage.setItem('user', JSON.stringify(values))
}
else {
localStorage.removeItem('user')
}
setTimeout(() => {
this.$router.push('/admin')
}, 1500)
}
else {
this.$message.error(res.msg);
this.imgCode = 'http://47.93.101.203/adminapi/captcha_pro?' + new Date()
}
})
}
});
},
},
};
</script>
<style scoped lang="less">
.login-bg {
width: 100%;
height: 100%;
background: red;
}
.polpe {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.login {
background: pink;
width: 50%;
text-align: center;
h2 {
text-align: center;
}
}
#components-form-demo-normal-login .login-form {
max-width: 300px;
}
#components-form-demo-normal-login .login-form-forgot {
float: right;
}
#components-form-demo-normal-login .login-form-button {
width: 100%;
}
</style>
//src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from "./module/user.js"
import vuexPersistedstate from "vuex-persistedstate"
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
user,
},
plugins: [
vuexPersistedstate({
key: "use",
storage: window.localStorage
})]
})
//src/store/module/user.js
export default {
state: {
userInfor: {},
},
getters: {
},
mutations: {
//同步方法
getuserInfor(state, value) {
state.userInfor = value
}
},
actions: {
//异步调用同步方法
getuserInforAsync(context, value) {
context.commit('getuserInfor', value)
}
},
namespaced: true,//命名空间
}