axios實作資料(模拟資料)請求
1、在終端運作以下指令,安裝axios
npm install axios --save
2、進行需求分析,在本例中首頁Home元件中有Header、Swiper、Icons、Recommend、Weekend等5個子元件需要進行資料綁定。換言之,我們需要發起5次ajax請求,但是頻繁發起ajax請求,網站的性能必定是很低的。是以,我們需要盡量減少網絡請求的次數,我們可以通過父元件Home發起資料請求,然後把資料傳給子元件就可以了。
3、利用axios發起網絡請求的步驟
(1)首先,在父元件Home中引入,在mounted鈎子中發起請求
import axios from "axios"
import axios from "axios"
import HomeHeader from "./components/Header";
import HomeSwiper from "./components/Swiper"
import HomeIcons from "./components/Icons"
import HomeRecommend from "./components/Recommend"
import HomeWeekend from "./components/Weekend"
export default {
name: "Home",
data() {
return {
city: '',
iconList:[],
recommendList:[],
swiperList:[],
weekendList:[]
};
},
components: {
HomeHeader,
HomeSwiper,
HomeIcons,
HomeRecommend,
HomeWeekend
},
mounted(){
this.getHomeInfo();
},
methods: {
getHomeInfo(){
// axios傳回的結果是一個promise對象
axios.get('/api/index.json').then(
// 注意:這裡絕對不可以寫成this.getHomeInfoSucc(),否則請求的結果會是undefined
this.getHomeInfoSucc
)
},
getHomeInfoSucc(res){
console.log(res);
res = res.data;
if (res.ret && res.data) {
this.city = res.data.city;
this.swiperList = res.data.swiperList;
this.iconList = res.data.iconList;
this.recommendList = res.data.recommendList;
this.weekendList = res.data.weekendList;
}
}
}
};
(2)在沒有後端支援的時候,我們可以通過json檔案進行資料模拟。但是,對應的json檔案應該放在什麼位置呢?在vue項目目錄中,static檔案夾是存放的靜态檔案,隻有該檔案夾下的檔案可以被外界通路到(驗證方法:位址欄輸入對應static檔案夾下面json檔案的正确路徑如:http://localhost:8080/static/mock/index.json)。發現,對應的模拟資料index.json檔案的内容,可以看到,如下:
(3)此外,對于模拟資料,我們不希望把它們上傳至線上,應該怎麼處理呢?其實,很簡單,我們隻要忽略上傳它們即可。具體做法是:打開.gitignore檔案,在忽略的檔案中,我們添加上模拟資料所在的檔案路徑(static、mock)即可。如圖:
proxyTable: {
'/api': {
target: 'http://localhost:8080', //設定轉化的域
pathRewrite:{
'^/api': '/static/mock' // 路徑替換
}
}