
vuex官方示意圖
整個(gè)流程:首先確保是否有異步請(qǐng)求或者異步操作在整個(gè)vuex的流程中,如果有就在
actions里面進(jìn)行操作,在操作之前需要發(fā)一條消息(this.$store.dispatch(' '))給actions用于接收。接收之后發(fā)起請(qǐng)求或者異步操作,然后再commit一條消息給mutations,用于修改state里面的數(shù)據(jù)(store.commit(' ',data))。
以下是一個(gè)完整的栗子。比如在項(xiàng)目中有一個(gè)推薦的列表,可以來(lái)回的切換,但不需要每次在切換的時(shí)候都要去請(qǐng)求一次數(shù)據(jù),這樣會(huì)浪費(fèi)請(qǐng)求的事件還要多次更新html,所以就利用vuex來(lái)完成。
首先在項(xiàng)目下新建一個(gè)store文件夾,分別引入vue和vuex,以及在vue中注冊(cè)vuex
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);
接著寫(xiě)入以下內(nèi)容
const store=new Vuex.Store({
state:{
},
actions:{ //在這里處理異步請(qǐng)求(也可以處理同步請(qǐng)求),但是改變狀態(tài)還是需要在mutations里面進(jìn)行修改,所以需要commit
},
mutations:{//在這里處理同步請(qǐng)求,改變state里面的數(shù)據(jù),不能異步(比如加定時(shí)器)
}
})
export default store;
然后在main.js中引入并且注冊(cè)到vue中。
import Vue from 'vue'
import App from './App'
import router from './router'
import store from '../store/index';
new Vue({
el: '#app',
router,
store,
components: { App },
template: '<App/>'
})
而我們的項(xiàng)目需要正如上面所說(shuō),不需要來(lái)回的請(qǐng)求數(shù)據(jù),所以我們?cè)陧?yè)面中就需要這么一段if判斷。
if(this.$store.state.recommendList.length===0&&this.$store.state.bannerImg){
//我們需要判斷store里面state的recommendList和bannerImg是否有值,如果沒(méi)有的話我們就需要dispatch一條消息給actions,告訴actions需要請(qǐng)求。
this.$store.dispatch('getRecommendList')
}
然后來(lái)到store下面的index.js中
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);
const store=new Vuex.Store({
state:{
recommendList:[],
bannerImg:[]
},
actions:{ //在這里處理異步請(qǐng)求(也可以處理同步請(qǐng)求),但是改變狀態(tài)還是需要在mutations里面進(jìn)行修改,所以需要commit
getRecommendList:function(store){
axios.get('/v2/page',{
params:{
pageId:1,
tabId:1,
currentPage:1,
pageSize:8,
_:1556056259410
}
}).then(res=>{
let length=res.data.data.modules.length;
//在actions里面并不能修改state 所以需要commit一條消息給mutations,讓mutations里面的函數(shù)來(lái)修改掉狀態(tài)。
store.commit('setRecommendList',res.data.data.modules.slice(1,length))
store.commit('setRecommendBannerImg',res.data.data.modules[0].moduleContent.banners)
})
}
},
mutations:{//在這里處理同步請(qǐng)求,改變state里面的數(shù)據(jù),不能異步(比如加定時(shí)器)
setRecommendList:function(state,payLoad){
state.recommendList=payLoad;
},
setRecommendBannerImg:function(state,payLoad){
state.bannerImg=payLoad;
}
}
})
export default store;