1.在建好的vue項目中新建一個vuex文件夾在此文件夾下建一個index.js文件,在此文件下引入vuex 模塊(當然需要先npm下載)和vue模塊,在引入你所有的自定義的module.js模塊(下邊會講module的內容),然后使用vuex
Vue.use(Vuex) ;在導出時新創建一個Vuex的Store的對象,在這個對象中使用modules:{把你自定義的模塊賦值}代碼如下:
import Vuex from 'vuex'
import Vue from 'vue'
import home from '../page/home/moudlehome.js';
import city from '../page/city/moudlecity.js';
Vue.use(Vuex);
export default new Vuex.Store({
modules:{
home:home, //this.$store.state.home
city:city //this.$store.state.city
}
})
2.在module.js中使用vuex的核心內容並發送axios請求(前提是在頁面渲染完后就發送請求所以需要在總組件中設置mounted() { if(this.$store.getters.shouldGetData){
this.$store.dispatch("getSwiperInfo");
} }來傳值給module中的actions並且在getSwiperInfo()函數中發送axios異步請求,代碼如下:
import axios from 'axios';
export default {
//數據內容
state:{
swiperInfo: [],
swiperInfo1: []
},
//異步操作
actions:{
getSwiperInfo(context){
axios.get('/static/index.json')
.then((response)=>{
if (response.status === 200) {
const {data} = response.data;
context.commit("changeSwiperInfo",data)
}
})
}
},
//對數據內容的更新
mutations:{
changeSwiperInfo:(state,data)=>{
state.swiperInfo = data.swiperInfo;
state.swiperInfo1 = data.swiperInfo1
}
},
//對數據的二次包裝對網頁的一種優化
getters:{
shouldGetData(state){
if(!state.swiperInfo.length&&
!state.swiperInfo1.length){
return true;
}else{
return false;
}
}
}
}
3.在子組件中綁定並使用數據、
在子組件中使用
computed:{
swiperInfo(){
return this.$store.state.home.swiperInfo;
}
}
綁定數據
然后就可以在你的實例化循環中使用swiperInfo in item來使用數據了