单页面使用
单页面使用 state
this.$store.user.userName
import { mapState } from "vuex";
export default {
computed:{
...mapState('user/',{
usName : s => s.userName
}),
}
}
this.usName
单页面使用 getters
import { mapGetters } from "vuex";
export default {
computed:{
...mapGetters ('user/',{
usName : 'userName'
}),
}
}
this.usName
单页面使用 mutations
import { mapMutations } from 'vuex'
export default {
methods: {
...mapMutations([
'increment',
'incrementBy'
]),
...mapMutations({
add: 'increment'
})
}
}
this.increment()
this.incrementBy()
this.add()
单页面使用 actions
import { mapActions } from 'vuex'
export default {
methods: {
...mapActions([
'increment',
'incrementBy'
]),
...mapActions({
add: 'increment'
})
}
}
this.increment()
this.incrementBy()
this.add()
单模块使用
在vuex单模块内综合使用
state:{
count:0
}
mutations: {
someMutation(state) {
state.count++
}
}
actions: {
actionA ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('someMutation')
resolve()
}, 1000)
})
},
actionB ({ dispatch, commit }) {
return dispatch('actionA').then(() => {
commit('someOtherMutation')
})
}
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA')
commit('gotOtherData', await getOtherData())
}
}
跨模块使用
store 普及
其中有:
commit,
dispatch,
state,
rootState,
rootGetters,
getters
state
const actions = {
async login(store, config = {}) {
const { rootState } = store
rootState.user.userName
}
}
getters
const actions = {
async login(store, config = {}) {
const { rootGetters } = store
rootGetters['vip/get']
}
}
mutations
const actions = {
async login(store, config = {}) {
const { commit } = store
commit('vip/receive', data, {root: true})
}
}
actions
const actions = {
async login(store, config = {}) {
const { dispatch } = store
dispatch('vip/get', {}, {root: true})
}
}