axios
- 獲取后臺數(shù)據(jù)的方法插件
promise
- 處理異步的方法
封裝
- 在實(shí)際項目里為了更方便的使用axios獲取后臺數(shù)據(jù),這里我們用promise封裝一下
vue項目里封裝方法我們一般放在utils文件夾里
src下新建一個utils文件夾叶圃,index.js文件
/* eslint-disable no-unused-vars */
import axios from 'axios';
// const get = () => {
// console.log('get請求');
// }
// const post = () => {
// console.log('post請求')
// }
// export{
// get,
// post
// }
// process.env.NODE_ENV環(huán)境
let baseURL;
if(process.env.NODE_ENV=='development'){
baseURL = 'http://132.232.94.151:3000/api'
}else{
baseURL = '/xxx'
}
// baseURL es6 方法
const $http = axios.create({
baseURL,
})
// create 是axios自帶的方法
export const get = (url,params)=>{
params = params || {};
return new Promise((resolve,reject)=>{
// axiso 自帶 get 和 post 方法
$http.get(url,{
params,
}).then(res=>{
if(res.data.status===0){
resolve(res.data);
}else{
alert(res.data.msg)
}
}).catch(error=>{
alert('網(wǎng)絡(luò)異常');
})
})
}
export const post = (url,params)=>{
params = params || {};
return new Promise((resolve,reject)=>{
$http.post(url,params).then(res=>{
if(res.data.status===0){
resolve(res.data);
}else{
alert(res.data.msg);
}
}).catch(error=>{
alert('網(wǎng)絡(luò)異常');
})
})
}
這里用到了的知識點(diǎn)
1.baseURL
2.axios的create方法
3.promise以及axios的get和post
main.js方面
import { get, post } from "./utils/index";
Vue.prototype.$http = {
get,
post
};
1.這里使用了構(gòu)造函數(shù)的原型prototype(vue屬于構(gòu)造函數(shù))
2.聲明一個全局變量并且把封裝好的get和post方法放在里面
使用封裝后的函數(shù)
created() {
this.getFilmList();
},
methods: {
async getFilmList() {
const url = "/film/getList";
// 要訪問第二頁的話在網(wǎng)址后面加 ?type=2&pageNum=頁數(shù)
const res = await this.$http.get(url);
this.filmList = res.films;
},
這里注意的是袄膏,因為是promise封裝的函數(shù)方法,所以使用的時候要加上
async 函數(shù)(){ await 數(shù)據(jù)} 不然會報錯掺冠,因為沒有完成異步轉(zhuǎn)同步