1.state访问状态
count.vue中引入import { mapState } from 'vuex'
computed中写法
(1)方法一:
computed:mapState({ count:state=>state.count})
(2)方法二:
computed:mapState(['count'])
template中可直接使用
{{count}} 获取到值
2.mutations修改状态
在count.vue中,使用commit来修改其状态
<button @click="$store.commit('add')"></button>
在store.js中写法
const mutations= {
add(state){
state.count++
}
}
也可进行传值,在commit中第二个参数,输入添加的值
<button @click="$store.commit('add,10')"></button>
store.js文件中,
const mutations= {
add(state,n){
state.count +=n
}
}
使用模板获取mutations的方法
count.vue中,引入mapMutations
import { mapState,mapMutations } from ;vuex'
methods:mapMutations(['add','reduce'])
template中使用
<button @click="add"></button>
3.计算属性getters
首先,在store.js中申明
const getters = {
count:function(state){
return state.count +=100
}
}
在export default 中加入getters这个属性,
在count.vue中使用
(1)使用方法一
computed:{
...mapState(['count'])
count(){
return this.$store.getters.count
}
}
(2)使用方法二
引入mapGetters
import { mapGetters } from 'vuex'
在computed中加入
...mapGetters(['count'])
4.actions 异步修改状态
在store.js中申明
const actions = {
addActions(context){
context.commit('add',10)
},
reduceActions(context){
context.commit('reduce')
}
}
count.vue中使用
<button @click="addAction">+</button>
<button @click="reduceAction">-</button>
引入mapGetters
import { mapGetters } from 'vuex'
methods中使用
...mapActions(['addActions','reduceAction'])
5.modules模块组
在store.js中申明模块组
const moduleA = {
state,mutations.getters.actions
}
修改原来Vuex.Store中的值
export default new Vuex.Store({
modules:{a.moduleA}
})
在count.vue中的使用方法
(1)插值的方式
<h2>{{$store.state.a.count}}</h2>
(2)简单的引入方式
computed:{
count(){
return this.$store.state.a.count
}
}
在template中直接使用{{count}}的形式
本文来源技术胖的博客,附上地址,http://jspang.com/post/vuex.html