一、配置Vuex
安装Vuex
npm install --save vuex
创建Vuex核心管理对象模块
创建store.js
,一般置于目录@/src/
下
// vuex的核心管理对象模块
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
// 状态对象
const state = {};
// 包含多个更新state函数的对象
const mutations = {};
// 包含多个对应事件回调函数的对象
const action = {};
// 包含多个getter计算属性函数的对象
const getters = {};
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
有时候在实际项目中,对象state, mutations, actions, getters可能会放在单独的模块文件中。
在main.js
中引入store.js
import store from './store'
new Vue({
el: '#app',
components: { App },
template: '<App/>',
store
})
store对象
所有用vuex管理的组件中都多了一个属性$store, 它就是一个store对象。
包含属性:
state:注册的state对象
getters: 注册的getters对象
包含方法:
dispatch:分发方法
二、Vuex实例
需求:编写一个简单的点击计数器,能够判断当前次数的奇偶。包含四个按钮,分别为计数加一、计数减一、当次数为奇数时加一和异步加一。
App.vue
template
<template>
<div>
<p>click {{ count }} times, count is {{ evenOrOdd }}</p>
<button @click="increment">+</button>
<button @click="decrement">-</button>
<button @click="incrementIfOdd">increment if odd</button>
<button @click="incrementAsync">increment async</button>
</div>
</template>
script
<script>
export default {
computed: {
count () {
return this.$store.state.count
},
evenOrOdd () {
return this.$store.getters.evenOrOdd
}
},
methods: {
increment () {
// 通知vuex去增加
this.$store.dispatch('increment')
},
decrement () {
// 减少
this.$store.dispatch('decrement')
},
incrementIfOdd () {
// 如果是奇数才增加
this.$store.dispatch('incrementIfOdd')
},
incrementAsync () {
// 过一秒才增加
this.$store.dispatch('incrementAsync')
}
}
}
</script>
store.js
state
const state = {
// 初始化状态
count: 0
};
mutations
const mutations = {
// 增加的mutation
INCREMENT(state) {
state.count ++ ;
},
// 减少的mutation
DECREMENT(state) {
state.count -- ;
}
};
actions
const actions = {
increment({commit}) {
// 增加的action
// 提交增加的mutation
commit('INCREMENT');
},
decrement({commit}) {
// 增加的action
// 提交减少的mutation
commit('DECREMENT');
},
// 带条件的action
incrementIfOdd({commit, state}) {
if(state.count % 2 === 1) {
commit('INCREMENT');
}
},
// 异步的action
incrementAsync({commit}) {
// 在action中直接就可以执行异步代码
setTimeout(() => {
commit('INCREMENT');
}, 1000)
}
};
getters
const getters = {
evenOrOdd(state) {
// 不需要调用,只需要读取属性值
return state.count % 2 === 0 ? '偶数' : '奇数';
}
};
三、使用API简化代码
使用map(映射) API简化代码
mapState
mapActions
mapGetters
这些函数返回值均为对象类型。
首先在App.vue中script部分导入:
import { mapState, mapActions, mapGetters } from 'vuex'
使用:
<script>
import { mapState, mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapState(['count']),
...mapGetters(['evenOrOdd']) // 此时该函数的返回值为:{ evenOrOdd() { return this.$store.getters['evenOrOdd'] } }
},
methods: {
...mapActions(['increment', 'decrement', 'incrementIfOdd', 'incrementAsync'])
}
}
</script>
- 点击事件的回调函数名要与store中的action名尽量保持一致
- 当不一致时,例如事件回调函数名为name1, action名为name2的用法为:
…mapGetters({ name1: 'name2' })