Vuex 介绍
-
Vuex 是什么?
Vuex 官网: https://vuex.vuejs.org/zh/
Vuex 是一种状态管理模式,简单讲就是通过初始化 Store,配置 state(存数据),mutations(处理数据的方法), actions(异步处理数据方法),getters(类似组件里面的 computed )等,集中处理数据;
-
为什么要集中处理数据 ?
- 如果你的项目组件之间数据传值相关功能少,数据相关业务逻辑简单,使用父子组件传值、Bus总线传值即可,不必使用 Vuex;
- 如果项目业务逻辑复杂,组件之间需要频繁传参,甚至各个组件之间需要同步响应,那么最好使用 Vuex 进行数据集中处理;
Vuex 简单使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<!-- 1. 组件 直接使用 state -->
{{ this.$store.state.count }}
<!-- 2. 组件 通过计算属性使用 state -->
{{ newMsg }}
<button @click="add()">增加</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.5.1/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment(state) {
state.count++
}
}
})
var app = new Vue({
el: '#app',
data: {
msg: 'message'
},
computed: {
newMsg() {
return this.$store.state.count;
},
},
methods: {
add() {
// 组件 调用 mutations 的方法
this.$store.commit('increment');
}
},
store
});
</script>
</body>
</html>
Vuex 使用速查
定义 | 组件中使用 | 简化方式 |
---|---|---|
state.a | this.$store.state.a | computed: { …mapState([ a ]) } |
mutations.b | this.$store.commit(‘b’) | methods: { …mapMutations([‘b’])} |
acions.c | this.$store.dispatch(‘c’) | methods: { …mapActions([‘c’])} |
getters.d | this.$store.getters.d | computed: { …mapGetters([d])} |
states、mutations、actions
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
{{ msg }}
{{ num }}
<button @click="countAdd()">count 增加</button>
<button @click="numAsyncAdd()">num 增加</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex@3.5.1/dist/vuex.js"></script>
<script>
const store = new Vuex.Store({
state: {
count: 0,
num: 2
},
mutations: {
increment(state) {
state.count++;
},
numAdd(state) {
state.num++;
}
},
actions: {
changeAsync(context) {
// context.state.num
// 使用 setTimeout 模拟异步请求
setTimeout(() => {
context.commit('numAdd');
}, 1000)
}
}
})
var app = new Vue({
el: '#app',
data: {
},
computed: {
// 如果 vuex 通过 js 引入,使用 ...Vuex.mapState
// 如果是模块化引入 vuex ,使用 ...mapState()
// msg() {
// return this.$store.state.count
// },
// num() {
// return this.$store.state.num
// },
...Vuex.mapState({
msg: 'count',
num: 'num',
})
},
methods: {
// countAdd() {
// this.$store.commit('increment');
// },
...Vuex.mapMutations({
countAdd: 'increment'
}),
// numAsyncAdd() {
// this.$store.dispatch('changeAsync');
// },
...Vuex.mapActions({
numAsyncAdd: 'changeAsync'
}),
},
store
});
</script>
</body>
</html>
总结
- Vuex 适合复杂组件传参使用,例如:购物车;
- Vuex 核心:state(存数据),mutations(处理数据的方法), actions(异步处理数据方法);
- 数据处理请放到 mutations 或者 actions 里面,组件中不要直接操作 state 里面的数据,只是通过分发的形式(commit、dispatch)进行;