1. 向外暴露store对象
store.js
/**
* vuex的核心管理对象模块:store
*/
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
//状态对象
const state ={}
// 包含多个直接更新 state 的方法(回调函数)的对象
const mutations = {}
// 包含多个事件回调函数的对象
const actions = {}
// 包含多个计算属性(get)的对象
const getters = {}
export default new Vuex.Store({
state, //状态对象
mutations, // 包含多个直接更新 state 的方法(回调函数)的对象
actions, // 包含多个事件回调函数的对象
getters // 包含多个计算属性(get)的对象
})
2. 映射store
import store from './store'
new Vue({
store
})
3. store对象
- 所有用 vuex 管理的组件中都多了一个属性
$store
, 它就是一个 store 对象 - 属性:
state: 注册的 state 对象
getters: 注册的 getters 对象 - 方法:
dispatch(actionName, data)
: 分发调用 action
4. 使用过程
- 触发函数(App.vue)
<button @click="increment">+</button>
- 定义函数方法(App.vue)
methods: {
//增加
increment () {
// 通知vuex去更新
this.$store.dispatch('increment') // 分发调用 action
}
}
- dispatch action(store.js)
定义state
const state = {
count: 0
}
const actions = {
increment ({commit}) {
// 提交增加mutation
commit('INCREMEMT')
}
}
- commit mutation(store.js)
const mutations = {
//增加
INCREMEMT (state) {
state.count++
}
}
5. 编码简化
首先引入
import {mapState, mapGetters, mapActions} from 'vuex'
简化后的编码
computed: {
...mapState(['count']),
...mapGetters(['evenOrOdd'])
},
methods: {
...mapActions([
'increment',
'decrement',
'incrementIfOdd',
'incrementAsync'
])
},
补充,当命名不一致时
store.js
const getters = {
evenOrOdd2 (state) { // 不需要调用,只需要读取属性值
return state.count%2===0 ? '偶数' : '奇数'
}
}
App.vue
<p>{{evenOrOdd}}</p>
<script>
import {mapState, mapGetters, mapActions} from 'vuex'
export default {
computed: {
...mapGetters({evenOrOdd: 'evenOrOdd2'})
},
}
</script>