uniapp 之 常用的 main.js文件配置 上

前言

在我们日常工作开发中,每次新建一个uniapp项目,所使用的main.js文件中的内容大差不差,

我这边的话,先分享下我自己所使用的 内容,也是为了方便下次使用时可以直接C过去

若有大神使用的内容比我好的话,欢迎留言

总代码

// #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

分析

1.引入

@escook/request-miniprogram

因平台的限制,小程序项目中不支持 axios,而且原生的 wx.request() API 功能较为简单,不支持拦截器等全局定制的功能。因此,建议在 uni-app 项目中使用 @escook/request-miniprogram 第三方包发起网络数据请求。 

官网

下载安装   

npm install @escook/request-miniprogram

最终配置

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()
}

配置完成后就是将 

将$http挂载到全局
uni.$http = $http

请求时

uni.$http.get/ post(‘请求地址’ ,参数)  

猜你喜欢

转载自blog.csdn.net/LJM51200/article/details/128374052