Subcontract configuration of uniapp applet, initiate request call interface, encapsulate showMsg prompt box, page jump

1. Configure subcontracting of applets

Subpackaging can reduce the loading time of applets when they are first launched. For this reason, in the project, we put tabBar related pages into the main package, and other pages into subpackages. In the uni-app project, the steps to configure subcontracting are as follows:

1. In the project root directory, create a subpackage root directory named subpkg

2. In pages.json, declare the subPackages node at the same level as the pages node, which is used to define the subpackage-related structure

{
  "pages": [  // tabBar 相关页面
    {
      "path": "pages/home/home",
      "style": {}
    }...  ...
  ],
  "subPackages": [  // 分包相关页面
    {
      "root": "subpkg",
      "pages": []
    }
  ]
}

3. Right click on the subpkg directory, click the New Page option, and fill in the relevant information of the page

2. Initiate a request in the applet

1. Configure network requests

Due to the limitation of the platform, axios is not supported in the applet project, and the original wx.request() API function is relatively simple, and does not support global customization functions such as interceptors. Therefore, it is recommended to use the @escook/request-miniprogram third-party package in the uni-app project to initiate network data requests. In the main.js entry file of the project, configure it in the following way:

Please refer to the official documentation of @escook/request-miniprogram for installation, configuration and use
Official document: https://www.npmjs.com/package/@escook/request-miniprogram
import { $http } from '@escook/request-miniprogram'

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

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

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

2. Request the data of the carousel

2.1 Implementation steps

  1. Define the array of carousels in data

  1. Call the method of obtaining carousel data in the onLoad lifecycle function

  1. Define the method of obtaining carousel data in methods

2.2 Sample code

      export default {
        data() {
          return {
            swiperList: [],
          }
        },
        onLoad() {
          this.getSwiperList()
        },
        methods: {
          async getSwiperList() {
            const { data: res } = await uni.$http.get('/api/public/...')
            if (res.meta.status !== 200) {
              return uni.showToast({
                title: '数据请求失败!',
                duration: 1500,
                icon: 'none',
              })
            }
            this.swiperList = res.message
          },
        },
      }

2.3 Render UI structure

      <template>
        <view>
          <!-- 轮播图区域 -->
          <swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" :circular="true">
            <!-- 循环渲染轮播图的 item 项 -->
            <swiper-item v-for="(item, i) in swiperList" :key="i">
              <view class="swiper-item">
                <!-- 动态绑定图片的 src 属性 -->
                <image :src="item.image_src"></image>
              </view>
            </swiper-item>
          </swiper>
        </view>
      </template>

3. Call the interface get/post that needs to carry parameters

      async login() {
        const data/param = {
          phone:this.phone,
          password:this.password,
        };
        const res = await uni.$http.get/post('/api/public/...', data/param)
        if (res.code == '200') {
          // 其他操作或调用其他方法
         return uni.showToast({
           title: '登录成功!',
           duration: 1500,
           icon: 'success',
         })
        } else {
          return uni.showToast({
           title: '登录失败,请重试!',
           duration: 1500,
           icon: 'none',
         })
        }
      },

3. Encapsulate the uni.$showMsg() method

当数据请求失败或成功时,经常需要调用 uni.showToast({ }) 方法来提示用户。此时,可以在全局封装一个 uni.$showMsg() 方法,来简化 uni.showToast() 方法的调用。具体的改造步骤如下:

1. 在 main.js 中,为 uni 对象挂载自定义的 $showMsg() 方法

      uni.$showErrorMsg = function (title = '失败!', duration = 1500) {
        uni.showToast({
          title,
          duration,
          icon: 'none'
        })
      }
      uni.$showSuccMsg = function (title = '成功!', duration = 1500) {
        uni.showToast({
          title,
          duration,
          icon: 'success'
        })
      }

2. 在需要提示消息的时候,直接调用 uni.$showMsg() 方法

      async login() {
        const data = {
          phone:this.phone,
          password:this.password,
        };
        const res = await uni.$http.get('/admin/login', data)
        if (res.data.code == '200') return uni.$showSuccMsg('登陆成功!')
        if (res.data.data == '登陆失败') return uni.$showErrorMsg('登陆失败!')
      },

三、小程序的跳转方式

navigateTo:保留当前页,跳转到另一个页面,有返回按键

redirectTo:关闭当前页,重定向到其他页面,没有返回按键

switchTab:跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面

navigateBack:返回一级或多级

uni.switchTab({  // 底部tabbar页面跳转
   url: '/pages/home/home'
})

uni.navigateTo({ // 其他页面跳转
   url: `/subpkg/mingxi/mingxi`
})

getItem() {
   money = this.money
   time = this.time
   uni.navigateTo({  // 携带参数跳转
     url: `/subpkg/mingxi/mingxi?money=${money}&time=${time}`
   })
}

Guess you like

Origin blog.csdn.net/m0_61663332/article/details/129613126