uniapp encapsulates and globally mounts the request request

foreword

     In daily development, the front-end project needs to call the server-side api to complete page rendering. The request api provided by uniapp is uni.requestrelatively cumbersome; in addition, different apis provided by the server only have different sub-paths, and the api domain name and root path are the same. Once the interface api There will be many changes that need to be changed. In view of the above, it can be uni.requestpackaged to simplify development. At present, the uniapp project supports two versions of vue2 and vue3.
Regardless of vue2 or vue3, it can be divided into three steps: encapsulating request, global mounting, Use. Different versions have different mount processing methods. The corresponding implementations are described below:

1. Package request

     Create the untils folder for the project and directory, create api.js, and package it as follows:

  const BASE_URL="项目固定路径,例如:http://abc.com/api"
  // 向外暴露一个方法 myRequest
  export const myRequest = (options) => {
    
     
      //加载loading
      uni.showLoading({
    
     
          title:'数据加载中'
      })
      return new Promise((resolve, reject) => {
    
     
          uni.request({
    
     
              // 开发者服务器接口地址(请求服务器地址 + 具体接口名)
              url: BASE_URL + options.url,
              // 请求方式(若不传,则默认为 GET )
              method: options.method || 'GET',
              // 请求参数(若不传,则默认为 {
    
    }
              data: options.data || {
    
     },
              // 请求成功
              success: (res) => {
    
     
                  // 此判断可根据自己需要更改
                  if (res.data.status !== 1) {
    
     
                       return uni.showToast({
    
     
                           title: '获取数据失败!'
                       })
                   }
                  // 响应成功执行
                  resolve(res)
              },
              // 请求失败
              fail: (err) => {
    
     
                  uni.showToast({
    
     
                      title: '请求接口失败!'
                  })
                  // 响应失败执行
                  reject(err)
              },
              //请求结束之后,执行的回调函数(成功或失败都会执行)
              complete() {
    
     
                  //隐藏loading
                  uni.hideLoading()
              }
          })
      })
  }

2. Global mount

     Global mounting is implemented in main.js, and the mounting method will vary depending on the vue version of the project. Vue2 can use Vue.prototype, but not in vue3. For specific reasons, please refer to the official document: https:// cn .vuejs.org/api/application.html#app-config-globalproperties .
     To view the vue version of the project, refer to the following path:
     check the manifest.json in the project and directory as follows:
insert image description here

     Implementation of main.js mounting in vue2:

import App from './App'

// 以下在vue3外生效
// #ifndef VUE3
import Vue from 'vue';
import {
    
    myRequest} from './utils/app.js';

// 生产环境禁用常见的错误提示
Vue.config.productionTip = false

// 挂载myRequest
Vue.prototype.$myRequest=myRequest

App.mpType = 'app'
// 创建vue实例
const app = new Vue({
    
    
    ...App
})
// 挂载vue实例
app.$mount()
// #endif

// #ifdef VUE3
import {
    
     createSSRApp } from 'vue'
export function createApp() {
    
    
  const app = createSSRApp(App)
  return {
    
    
    app
  }
}
// #endif

     Main.js mounting method in vue3:

import App from './App'

// 以下在vue3外生效
// #ifndef VUE3
import Vue from 'vue';
// 生产环境禁用警告来帮你对付常见的错误与陷阱
Vue.config.productionTip = false

App.mpType = 'app'
// 创建vue实例
const app = new Vue({
    
    
    ...App
})
// 挂载vue实例
app.$mount()
// #endif

// #ifdef VUE3
import {
    
     createSSRApp } from 'vue';
// 导入myRequest
import {
    
    myRequest} from './utils/app.js';
export function createApp() {
    
    
  const app = createSSRApp(App)
  // 挂载$myRequest
  app.config.globalProperties.$myRequest = myRequest;
  return {
    
    
    app
  }
}
// #endif

3. Encapsulate request calling method

     this.$myRequestreplaceuni.request

  this.$myRequest({
    
    
                 url: '/news/detail.php?cid=52&id=258'
             }).then(res => {
    
     
                console.log("返回数据"+JSON.stringify(res));
             }).catch(err => {
    
     
                 console.log(err)
             });

     The above is the processing method of request encapsulation for different versions in actual project development. If you feel helpful, please like and leave a message in the comment area!

Guess you like

Origin blog.csdn.net/weixin_43401380/article/details/128753019