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