vue/uni-app引入全局封裝的網絡請求


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>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM