使用vue框架時獲取后臺數(shù)據(jù),將axios封裝的代碼:
一.首先在src新建utils文件夾再建index.js文件,在此做數(shù)據(jù)的封裝.
import axios from 'axios';
// process.env.NODE_ENV環(huán)境
let baseURL;
if (process.env.NODE_ENV === 'development') {
baseURL = 'http://132.232.87.95:3000/api'
} else {
//生產(chǎn)地址
baseURL = '/xxxx'
}
// 配置baseUrl
const $http = axios.create({
baseURL,
})
export const get = (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)絡異常');
})
});
}
第二步到main.js 將封裝函數(shù)導入.
import {get,post} from './utils/index'//文件路徑自己看情況寫
Vue.prototype.$http = {
get,
post
}
第三步在到需要使用后臺數(shù)據(jù)的index.vue的頁面中引用(如my里面的index.vue)
export default {
data() {
return {
cinemas: []
};
},
created() {
this.getFilmList();
},
methods: {
async getFilmList() {
const url = "/cinema/getList";
const res = await this.$http.get(url);
this.cinemas = res.cinemas;
}
}
};
第四步渲染頁面:
<div class="mg-t-15 bd-gray" v-for="(item,index) in cinemas" :key="index">
<div class="flex-sb">
<p class="f14 mg-l-15">{{item.name}}</p>
<p class="orangr f6 mg-r-15">
¥
<span class="f16">{{item.lowPrice/100}}</span>起
</p>
</div>
<div class="flex-sb mg-t-8 pd-b-15">
<p class="ell f12 gray mg-l-15">{{item.address}}</p>
<p class="gray f12 mg-r-15">{{item.Distance.toFixed(2)}}km</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
cinemas: []
};
},
created() {
this.getFilmList();
},
methods: {
async getFilmList() {
const url = "/cinema/getList";
const res = await this.$http.get(url);
this.cinemas = res.cinemas;
}
}
};
</script>