0、vuex使用Module
const moduleA = {
namespaced: true,
state: { ... },
getters: { ... },
mutations: { ... },
actions: { ... }
}
const moduleB = {
state: { ... },
getters: { ... },
mutations: { ... },
actions: { ... }
actions: {
someAction: {
root: true,
handler (namespacedContext, payload) { ... }
}
}
}
const store = new Vuex.Store({
modules: {
moduleA,
moduleB
}
})
import { createNamespacedHelpers } from 'vuex'
const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
複製代碼
- 在 store 建立以後,你能夠使用 store.registerModule 方法註冊模塊。
一、state
computed: {
count () {
return store.state.count
}
}
import { mapState } from 'vuex'
computed: mapState({
count: state => state.count,
countAlias: 'count',
'count',
countPlusLocalState (state) {
return state.count + this.localCount
}
})
computed: {
localComputed(){},
...mapState({
})
}
複製代碼
二、getter (store 的計算屬性)
getters: {
doneTodos: (state, getters) => {
return state.todos.filter(todo => todo.done)
},
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.doneTodos
computed: {
doneTodosCount () {
return this.$store.getters.doneTodosCount
}
}
import { mapGetters } from 'vuex'
computed: {
...mapGetters([
'doneTodosCount',
'anotherGetter',
])
}
複製代碼
三、Mutation (更改store狀態的惟一方法)
mutations: {
increment (state, payload) {
state.count = payload.count
}
}
store.commit('increment', {count: 10})
store.commit({ type: 'increment', amount: 10 })
import { mapMutations } from 'vuex'
methods: {
...mapMutations([
'increment',
'incrementBy'
])
}
複製代碼
四、 Action (提交mutation)
actions: {
increment (context) {
const state = context.state;
const s = context.getters;
context.commit('increment')
return new Promise((resolve, reject)=>{
});
}
}
store.dispatch('increment', {amount: 10})
store.dispatch({ type: 'incrementAsync', amount: 10 })
import { mapActions } from 'vuex'
methods: {
...mapActions([
'increment',
'incrementBy'
])
}
複製代碼
經常使用技巧
<input v-model="message">
computed: {
message: {
get () {
return this.$store.state.obj.message
},
set (value) {
this.$store.commit('updateMessage', value)
}
}
}
複製代碼