- State(必須)
- State是Vuex中唯一的數據源。在Vuex中定義,可以全局使用,一般在computed計算屬性中獲取,在頁面中渲染。
- 定義:
// store.js
store: {
count: 2
}
// 方法1:正常獲取
computed: {
count () {
return this.$store.state.count;
}
}
// 方法2: mapState輔助函數
import { mapState } from 'vuex'
computed: mapSate({
count: state=>state.count, // 箭頭函數
count: 'count', // 字符串傳參
count (state) { // 使用常規函數
return state.count;
}
})
computed: mapState(['count']) // 也可以傳遞字符串數組
// 方法3:mapState對象展開式
import { mapState } from 'vuex'
computed: {
...mapState({
count: 'count'
})
}
- Mutations(必須)
- 更改Store中狀態的唯一方法是提交Mutaion。
- 定義:
mutations: {
increment (state, n) {
state.count += n;
}
}
// 方法一:直接提交
this.$store.commit('increment', 10);
// 方法二:使用mapState引入
import { mapMutations } from 'vuex'
methods: {
...mapMutations([
'increment', 'add'
])
}
...mapMutations({
'add': 'increment' // 將 `this.add()` 映射爲 `this.$store.commit('increment')`
})
- Getters(非必須)
- 通過Getters可以派生出新的狀態。
- 通俗的講,Getters和State在Vuex中扮演着類似的功能,都是狀態的集合。假如某一個狀態本身被很多組件使用,但是有的地方又要改變這個數據的形式,這是就要使用Getters,比如購物車中的數量(當大於100時顯示99+)。Getters在組件中的獲取方式和State相同。
- 定義:
getters: {
doneTodos: state=>{
return state.todos.filter(todo => todo.done)
}
}
// 方法一:同Sate類似
return this.$store.getters.doneTodosCount
// 方法二:同Sate類似
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['doneTodosCount', 'anotherGetter'])
}
- Actions(非必須)
- Action提交的是Mutation,而不是直接變更狀態,Action可以包含任意異步操作。
- 定義:
// 方式一
actions: {
add (context) {
context.commit('increment');
}
}
// 方式二
actions: {
add ({commit}) {
commit('increment');
}
}
// 方式一:直接分發
this.$store.dispatch('add');
// 方式二:在組件中分發
import { mapActions } from 'vuex'
methods: {
...mapActions(['add', 'other']),
...mapActions({
add: 'increment' // 將 `this.add()` 映射爲 `this.$store.dispatch('increment')`
})
}
- Modules(非必須)
- 當應用變得非常複雜時,store 對象就有可能變得相當臃腫。爲了解決以上問題,Vuex 允許我們將 store 分割成模塊(module)。每個模塊都有自己的State、Getters、Mutations、Actions。
- 定義
const moduleA = {
state: { ... },
mutations: { ... },
actions: { ... },
getters: { ... }
}
const moduleB = {
state: { ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
a: moduleA,
b: moduleB
}
})
store.state.a // -> moduleA 的狀態
store.state.b // -> moduleB 的狀態