1、request.js文件
/*request.js*/
/* 封裝的網絡請求 */
export const request = params => {
const baseUrl = "https://api-hmugo-web.itheima.net/api/public/v1"
return new Promise((resolve, reject) => {
uni.request({
...params,
url: baseUrl + params.url,
success: res => {
if (res.statusCode !== 200) {
uni.showToast({
title: '獲取數據失敗',
duration: 800
});
} else {
resolve(res)
}
},
fail: err => {
uni.showToast({
title: "網絡請求失敗",
duration: 800
})
reject(err)
}
})
})
}
2、http.js文件
/*http.js*/
/* 使用網絡請求 */
import {request} from "./request.js"
/* 首頁輪播圖數據 */
export function getSwiperList(){
return request({
url:"/home/swiperdata"
})
}
/*main.js*/
import Vue from 'vue'
import App from './App'
import {getSwiperList} from "network/http.js"//引入網絡請求
Vue.prototype.$getSwiperList=getSwiperList //設置原型
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
3、index.vue文件
/*index.vue*/
<template>
<view class="index"></view>
</template>
<script>
/* 引入網絡請求模塊*/
// import { getSwiperList } from '../../network/http.js';
export default {
name: 'index',
data() {
return {
swiperList: [] //輪播圖數據
};
},
computed: {},
components: {},
created() {
this.getSwiperList();
},
mounted() {},
methods: {
/* 獲取輪播圖數據*/
async getSwiperList() {
// const res = await getSwiperList();
const res=await this.$getSwiperList();//使用網絡請求
console.log(res)
}
}
};
</script>
<style lang="scss" scoped></style>