Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
五大核心
state、mutations、actions、getters、modules
1、state
//state中声明状态count,初始值为0 初始值可以随便设一个
state: {
count: 0,
},
然后在组件中使用state值
a>在计算属性中可以通过this.$store.state.XXX来获取
//计算属性中获取state值
<template>
<div>
{{ this.HomeCount }} // 0
</div>
</template>
<script>
export default {
computed: {
HomeCount() {
return this.$store.state.count;
},
},
};
</script>
b>还可以使用辅助函数mapState来获取state的值
<template>
<div>
{{ this.count }} // 0
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
computed: {
...mapState(["count"]),
},
};
</script>
2、 mutations
更新修改state中的值必须使用mutations修改
a>在mutations中使用:
mutations: {
// 注意:mutations中形参只有两个,固定的state和val 如果要传递多个参数,val可以 以对象形式传递
addCount(state, val) { //通过state可以拿到state中的值 val为传递的参数
state.count += val;
},
},
b>组件中触发使用通过 this.$store.commit('触发函数',传递的值)
<template>
<div>
{{ this.count }}
<button @click="addCount">count+1</button>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
computed: {
...mapState(["count"]),
},
methods: {
addCount() {
this.$store.commit("addCount", 1);
},
},
};
</script>
3、actions
a>定义异步函数调用 mutations中的同步
mutations: {
addCount(state, val) {
state.count += val;
},
},
actions: {
addCountDelay(content) {
setTimeout(() => {
content.commit("addCount", 1);
}, 1000);
},
}
b> 组件中使用this.$store.dispatch('actions中的函数名')去修改state值
<template>
<div>
{{ this.count }}
<button @click="addCountDelay">count异步+1</button>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
computed: {
...mapState(["count"]),
},
methods: {
addCountDelay() {
this.$store.dispatch("addCountDelay");
},
},
};
</script>
4、getters
a>在getters中定义函数
getters: {
helloCount(state) {
return `hello${state.count}`;
},
},
b>获取通过getters操作的值
1、通过mapGetters辅助函数来获取值
<template>
<div>
{{ this.helloCount }}
</div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
computed: {
...mapGetters(["helloCount"]),
},
};
</script>
2、通过this.$store.getters.XXX
<template>
<div>
{{ this.helloCount }}
</div>
</template>
<script>
export default {
computed: {
helloCount() {
return this.$store.getters.helloCount;
},
},
};
</script>
5、modules
,可以让每一个模块拥有自己的state
、mutation
、action
、getters
,使得结构非常清晰,方便管理;如果所有的状态或者方法都写在一个store
里面,将会变得非常臃肿,难以维护。
modules参考链接:Vue --- Vuex中,modules的概念理解_LiuDevelop的博客-CSDN博客_vuex中modules