Vuex 共享数据小案例
案例介绍,在项目中有一个数据sum
,根据用户点击按钮可以对这个共享的数据sum
进行操作。
我有一个App.vue
,在其中我注册了一个组件CounterVue.vue
,所有的东西都在这个组件中,我将用这个组件来研究vuex。
这是vuex官网的原理图,所有的vuex代码都是围绕这个原理图来实现的。
组件逻辑
获取共享的数据(state)
在下面这段代码中,假设我需要给这个共享的数据,也就是sum
加一,我做了什么?或者说,经历了怎样的波折我们成功的操作到了数据?
首先,怎样拿到这个共享的sum
,我们知道,Actions
,Mutations
,State
都被store
所管理,而sotre
被vuex
挂载了原型链上。
所以我们可以通过this.$store
来拿到store
,并且再进一步拿到sum
的值。
修改数据
如何修改共享的数据?
- 第一步
根据原理图,我们需要通过store
对象的dispatch
方法来指定调用一个action
。例如,这里的this.$store.dispatch('jiaOdd', this.n)
就是调用了jiaOdd
这个Action
并传入了this.n
作为参数。 - 第二步
根据原理图,我们还需要提交这个Action
,也就是Commit
,这一步在index.js
中的Action
实际调用中才能得到体现。
CounterVue.vue
<template>
<div>
<h1>计数器: {{ $store.state.sum }}</h1>
<!-- 下拉框让用户选择加多大的数字 -->
<select v-model.number="n">
<option value="1">一次加 1</option>
<option value="2">一次加 2</option>
<option value="3">一次加 3</option>
<option value="4">一次加 4</option>
</select>
<button @click="decrement">-</button>
<button @click="increment">+</button>
<button @click="incrementOdd">奇数才加</button>
<button @click="incrementWait">等一会儿才加</button>
</div>
</template>
<script>
export default {
name: "CountCom",
data() {
return {
n: 1,
};
},
methods: {
increment() {
// 告诉store要执行jia的命令
this.$store.commit("JIA", this.n);
},
decrement() {
this.$store.commit('JIA', -this.n)
},
incrementOdd() {
this.$store.dispatch('jiaOdd', this.n)
},
incrementWait() {
this.$store.dispatch('jiaWait', this.n)
},
},
mounted () {
console.log(this)
}
};
</script>
<style scoped>
button {
margin-left: 10px;
}
</style>
store 中的逻辑
sotre>index.js
承接上文,vuex中的commit
一般用来直接地操作数据,所以如果是直接性的加或者减sum
就没有必要使用Action
,直接用Commit
操作即可。但如果需要一些业务逻辑的操作,就需要用到Action
,例如这里的奇数时才加(incrementOdd),和等待一会加(incrementWait)。
在Action
中处理完逻辑后,调用context.commit('JIA', value)
就实现了这里的奇数才加的功能。
这里有两个传参比较陌生,首先是jiaOdd(context, value)
,第二个参数是传入的值这个并不陌生。第一个参数是“上下文对象”,实际上就是一个具有主要功能的store
对象,虽然官方一般使用context
作为形参变量名,但实际上,用minStore
其实更加贴切。
还有一个就是JIA(state, value)
,这里的state
就是store
所管理的state
,vuex为他加上了getter
和setter
方法,可以响应式地更新模板的渲染。
import Vuex from "vuex";
import Vue from "vue";
Vue.use(Vuex)
// 准备actions用于响应组件中的动作
const actions = {
jiaOdd(context, value) {
if (state.sum % 2) {
context.commit('JIA', value)
}
},
jiaWait(context, value) {
setTimeout(() => {
context.commit('JIA', value)
}, 300);
}
}
// 准备mutations用于操作数据 (state)
const mutations = {
JIA(state, value) {
// state就是被store加工过的state,具有了getter和setter
state.sum += value
},
}
const state = {
sum: 0,
}
// 创建store
export default new Vuex.Store({
actions,
mutations,
state
})