vuex是vue中的狀態(tài)管理管理模式
公共的變量存放在state中妒茬,批量異步數(shù)據(jù)發(fā)生改變通過(guò)dispatch觸發(fā)相應(yīng)的action,然后通過(guò)commit觸發(fā)mutations進(jìn)而數(shù)據(jù)變化;也可以通過(guò)mutations進(jìn)行同步操作觸發(fā)數(shù)據(jù)變化坦胶。
store文件夾下的index.js文件
第一種情況
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
city:'北京'
},
actions:{
changeCity(ctx,city){
ctx.commit('changeCity',city)
}
},
mutations:{
changeCity(state,city){
state.city=city
}
}
})
觸發(fā)數(shù)據(jù)變化的頁(yè)面
<div class="button-wrapper" v-for="item of hot" :key="item.id" @click="handleCityClick(item.name)">
<div class="button">{{item.name}}</div>
</div>
methods:{
handleCityClick(city){
this.$store.dispatch('changeCity',city)
}
}//通過(guò)dispatch觸發(fā)action中的changeCity,同時(shí)將city傳入,觸發(fā)commit方法蓬痒,將變化數(shù)據(jù)city修改到state中
第二種情況
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{
city:'北京'
},
mutations:{
changeCity(state,city){
state.city=city
}
}
})
觸發(fā)數(shù)據(jù)變化的過(guò)程
methods:{
handleCityClick(city){
this.$store.commit('changeCity',city)
}
},