Open
Description
What problem does this feature solve?
Currently, we don't have mapXXX
helpers equivalent feature when using Vuex 4 in composition api. It would be nice to have as both a convenience and for better typing support.
What does the proposed API look like?
To smoothly support migration from Vuex 3, at first, we should align with existing mapXXX
helpers.
All of the following codes are meant to be used inside setup
hook.
useState
const { count, countAlias, countPlusLocalState } = useState({
// arrow functions can make the code very succinct!
count: state => state.count,
// passing the string value 'count' is same as `state => state.count`
countAlias: 'count',
// to access local state with `this`, a normal function must be used
countPlusLocalState (state) {
return state.count this.localCount
}
})
We should also support passing an array.
const { count } = useState([
// map this.count to store.state.count
'count'
])
useGetters
const { doneTodosCount, anotherGetter } = useGetters([
'doneTodosCount',
'anotherGetter'
])
Alias the name by passing an object.
const { doneCount } = useGetters({
doneCount: 'doneTodosCount'
})
useActions
const { increment, incrementBy } = useActions([
'increment', // map `increment()` to `store.dispatch('increment')`
'incrementBy' // map `incrementBy(amount)` to `store.dispatch('incrementBy', amount)`
])
const { add } = useActions({
add: 'increment' // map `add()` to `store.dispatch('increment')`
})
useMutations
const { increment, incrementBy } = useMutations([
'increment', // map `increment()` to `store.commit('increment')`
'incrementBy' // map `incrementBy(amount)` to `store.commit('incrementBy', amount)`
])
const { add } = useMutations({
add: 'increment' // map `add()` to `store.commit('increment')`
})
Namespacing
All useXXX
helpers should support passing namespace
as the first argument.
const { a, b } = useState('some/nested/module', {
a: state => state.a,
b: state => state.b
})
const { foo, bar } = useActions('some/nested/module', [
'foo',
'bar'
])
And finally, useNamespacedHelpers
.
const { useState, useActions } = useNamespacedHelpers('some/nested/module')
// look up in `some/nested/module`
const { a, b } = useState({
a: state => state.a,
b: state => state.b
})
// look up in `some/nested/module`
const { foo, bar } = useActions([
'foo',
'bar'
])
NOTE
There's an issue #1695 that proposes adding useModule
helper that returns the whole module
as an object. We could do the follow-up PR to tackle this idea as well.