Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
各个组件共享的数据即仓库(store)是唯一的
安装vuex
yarn add vuex
往仓库里存、取、改
存数据
在scr里面新建一个store文件夹 - index.js
在这个index.js里
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.store({
state:{
//所有的数据都写在这里面
n:666
}
})
在main.js
new Vue({
router,
render: h => h(App),
store //将这个加进去
}).$mount("#app");
取数据
在需要取store里面的数据的组件里写
//用计算属性
computed:{
n(){
return this.$store.state.n
}
}
再在页面上渲染,就可以取到仓库里的数据
改数据 -- 同步和异步
同步:
在这个store下的index.js里
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.store({
state:{
//所有的数据都写在这里面
n:666
},
//同步的方法放在mutations
mutations:{
changeN(state,payload){
//传多个参数要对象或者数组
state.n = state.n+payload
}
}
})
//组件里调用
<button @click="$store.commit('方法名',传的payload的实参)">+</button>
异步:要调用同步的方法来改变数据状态,形成单向数据流
mutations:{
musync(state){
//传多个参数要对象或者数组
state.n --
}
}
//异步的方法放在actions里
actions:{
方法名(context,payload){
//context是上下文参数
//传多个参数要对象或者数组
setTimeout(() => {
context.commit(mutations里的方法名musync)
},1000)
}
}
//组件里调用
<button @click="$store.dispatch('方法名',传的payload的实参)">-</button>
vue的单向数据流
图片.png
getters相当于vue里面的计算属性computed
//和state同级
//在js里面:
getters: {
zmxy(state) {
return state.n > 700 ? "信用极好的,你真棒!" : "信用优秀优秀";
}
}
//在组件的script里
computed:{
xy() {
return this.$store.getters.zmxy;
}
}
//组件的模板里:
{{xy}}
modules -- 分模块
1.分模块后,只有取数据时return this.$store.state.模块名(list).变量
在state后面加上模块名
2.分完模块之后getters里面不能重名,会报错,所以不能写重名的。
3.mutations和actions里面的方法 如果重名都会执行,解决方案:给模块加上命名空间
namespaced = true
//在Counter.js
export default{
namespaced: true
}
1.可以使用methods
methods: {
change(n) {
this.$store.commit("Counter/changeN", n);
}
}
<button @click="change(5)">同步+1</button>
2.可以不使用methods,直接写
<button @click="$store.commit('Counter/changeN', 5)">+1</button>
<!-- script里面两种方法都是这样写 -->
<script>
export default {
computed: {
n() {
return this.$store.state.Counter.n;
},
xy() {
return this.$store.getters["Counter/zmxy"];
}
}
};
</script>
四个辅助函数
1.mapState 把store里的状态映射到组件里
//如果分了模块
computed:{
...mapState(["模块名","state的变量名"])
}
//不分模块
...mapState(["state的变量名"])
模板里用的时候:模块名.变量名
2.mapGetters 把仓库里 的getters映射到组件里
//如果分了模块
computed:{
...mapGetters({
变量:"模块名/getters的变量名"
})
}
...mapGetters([
变量:"getters的变量名"
])
3.mapMutations 把仓库里 的同步方法映射到组件里
methods里
//分模块
...mapMutations({
方法名:"模块名/mutations的方法名"//必须改名才能用
})``
//不分模块
...mapMutations(["mutations的方法名"])
4.mapActions 把仓库里 的异步方法映射到组件里
methods里
//分模块
...mapActions({
方法名:["模块名/actions的方法名"]//必须改名才能用
})
//不分模块
...mapActions(["actions的方法名"])