Commonly used main.js file configuration of uniapp

foreword

In our daily work development, every time we create a new uniapp project, the content in the main.js file used is quite similar.

For my side, let me share the content I use first, so that I can go directly to C when I use it next time.

If there is a master who uses better content than me, please leave a message

total code

// #ifndef VUE3
import Vue from 'vue'
import App from './App'
import store from './store/store.js'
import share from './mixins/share.js'
Vue.mixin(share)
// 配置请求包
// 1.引入
import {
  $http
} from '@escook/request-miniprogram'
// 2.设置请求根路径
$http.baseUrl = 'https://loud.com'
// 3.设置拦截器-设置加载弹窗
$http.beforeRequest = function(options) {
  //打开弹窗提示用户正在加载
  uni.showLoading({
    title: "加载中..."
  })
  // 判断请求的是否为有权限的 API 接口
  if (options.url.indexOf('/uniapp') !== -1) {
    //设置Authorization请求头
    options.header.Authorization = `Bearer ${store.state.m_user.token}`
  }

  // 为请求头添加身份认证字段
  // options.header = {
  //   // 字段的值可以直接从 vuex 中进行获取
  //   Authorization: store.state.m_user.token,
  // }
}
$http.afterRequest = function({
  data: {
    resCode
  }
}) {
  // 关闭弹窗
  uni.hideLoading()
  if ("00100002" === resCode) {
    let n = 2
    uni.$showMsg(`当前状态异常,请先登录,页面将于${n}秒后跳转到登录页面`)
    let timer = setInterval(() => {
      n--
      if (n === 0) {
        clearInterval(timer)
        uni.navigateTo({
          url: '/pages/my/my'
        })
      }
      uni.$showMsg(`当前状态异常,请先登录,页面将于${n}秒后跳转到登录页面`)
    }, 3000)
    return
  }
  // console.log('响应拦截器', resCode, msg);
}
//4.将$http挂载到全局
uni.$http = $http
//uni.$http.get()  这个方法使用

// 封装弹窗
uni.$showMsg = function(title = '获取失败...') {
  uni.showToast({
    icon: "none",
    title
  })
}
Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
  ...App,
  store
})
app.$mount()
// #endif

analyze

1. Introduce

@escook/request-miniprogram

Due to platform limitations, axios is not supported in Mini Program projects , and the native  wx.request() API functions are relatively simple, and global customization functions such as interceptors are not supported . Therefore, it is recommended to use third-party packages in the uni-app project  @escook/request-miniprogram to initiate network data requests. 

official website

Download and install   

npm install @escook/request-miniprogram

final configuration

import { $http } from '@escook/request-miniprogram'

uni.$http = $http
// 配置请求根路径
$http.baseUrl = 'https://v.com'

// 请求开始之前做一些事情
$http.beforeRequest = function (options) {
  uni.showLoading({
    title: '数据加载中...',
  })
}

// 请求完成之后做一些事情
$http.afterRequest = function () {
  uni.hideLoading()
}

After the configuration is complete, the 

Mount $http to global
uni. $http = $http

on request

uni.$http.get/ post('request address', parameter)  

Guess you like

Origin blog.csdn.net/LJM51200/article/details/128374052