各位捧由,相信经过几天的研究後,我们现在对Vuex都有多一些的了解啦!
不晓得各位有没有觉得,在 Vue
元件中使用时,要一直用到 this.$store.state
、 this.$store.dispatch
很麻烦呢?
不想要过多的重复劳动,也想让程序码更简洁的话,我们就来研究一下 Vuex
的辅助函数吧!
state
可以使用辅助参数就是 mapState
,在 Vue
元件中怎麽使用呢?
首先要 import
import { mapState } from 'vuex'
以这段作为范例,如何使用 mapState
简洁我们的程序码呢?
export default {
// ...
computed: {
count () {
return this.$store.state.countModules.count
}
}
}
export default {
// ...
computed: mapState({
count: state => state.count,
}
})
}
state => state.count
export default {
// ...
computed: mapState({
countAlias: 'count',
})
}
this
获取局部状态,必须使用常规函数export default {
// ...
computed: mapState({
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
ES6
的展开运算符,将此对象混入到外部对象中computed: {
localComputed () { /* ... */ },
...mapState(['count'])
}
而且可以放不只一个哦,假设我们除了 count
还有 stateA
、stateB
,就可这样用
computed: {
localComputed () { /* ... */ },
...mapState(['count','stateA','stateB'])
}
count
放在 countModule
带命名模组中,是模组区域变数sateA
、 stateB
是全域变数,这样如何使用呢?computed: {
localComputed () { /* ... */ },
...mapState('countModules',['count'])
...mapState(['moduleA','moduleB'])
}
经过上面 mapState
的研究,我们对於使用方式应有一定的了解了
换作 mapGetters
、 mapMutations
、 mapActions
其实也都大同小异,一样我们需要先 import
import { mapGetters , mapMutations , mapActions } from 'vuex'
getter
部分跟 state
差不多,就不多补充说明罗!
export default {
// ...
computed: {
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}
以这段作为范例,要如何使用mapActions呢?
export default {
methods: {
updateCount () {
this.$store.dispatch('updateCount')
}
},
}
export default {
// ...
methods: {
...mapActions(['updateCount'])
}
}
updateCount
要增加多少数量,要另外传参数进入,如下范例:export default {
methods: {
updateCount (num) {
this.$store.dispatch('updateCount', num)
}
},
}
其实没关系,不用额外写什麽,直接可以传。
export default {
// ...
methods: {
...mapActions(['updateCount']),
//this.$store.dispatch('updateCount', num)
}
}
export default {
// ...
methods: {
...mapActions({
add: 'updateCount'
})
}
}
actions
如何使用呢?export default {
// ...
methods: {
...mapActions('countModules',['updateCount']),
})
}
}
mutations
部分跟 actions
差不多,就不补充说明罗。export default {
// ...
methods: {
...mapMutations([
'updateCount',
'updateCountBy'
]),
...mapMutations({
add: 'updateCount'
})
}
}
早起运动Day6 - 生日快乐我的国家 三点多有起来记录了一下梦话,接着再睡了回去,我想那是在...
前言 我们从一个简简单单的小菜,逐渐变成丰富的菜肴,今天要做的是选择权。看看会是怎样的食谱吧~ 本日...
此系列文章会同步发文到个人部落格,有兴趣的读者可以前往观看喔。 今天要跟大家分享当网站有用到Jav...
今天使用的范例出自高焕堂老师的书《AI机器人、蓝芽与Android整合开发技术》,需要完整程序码请参...
用户在使用服务的同时,其实就已经在个资隐私法规的保护之下享受服务需求,从用户第一次看到服务,到注册帐...