微信小程序从入门到进阶(二)

数据请求

wx.request发起网络请求,请求的方式主要分为两种:

  1. get 请求

  2. post 请求

typescript 复制代码
// get请求
// html
<view>
  <button type="primary" bindtap="onGetClick">发起 get 请求</button>
</view>
// js
// index.js
// 获取应用实例
onGetClick () {
    wx.request({
        url: 'https://api.imooc-blog.lgdsunday.club/api/test/getList',
        method: 'GET',
        success: (res) => {
            console.log(res);
        }
    })
}

// post请求
// html 
  <button type="primary" bindtap="onPostClick">发起 post 请求</button>
  // js
   onPostClick () {
    wx.request({
      url: 'https://api.imooc-blog.lgdsunday.club/api/test/postData',
      method: 'POST',
      data: {
        msg: '愿大家心想事成,万事如意'
      },
      success: (res) => {
        console.log(res);
      }
    })
  }
  1. 只能请求 HTTPS 类型的接口
  2. 必须将接口的域名添加到信任列表中

解决方案:

  1. 生产环境:将想要请求的域名协议【更改为 HTTPS】并【添加到域名信任列表】
  2. 开发环境:通过勾选
  3. 跨域问题: 跨域问题主要针对浏览器而言,而小程序宿主环境为【微信小程序客户端】,所以小程序中不存在【跨域问题】
  4. ajax请求:ajax 依赖于 XMLHttpRequest 对象,而小程序宿主环境为【微信小程序客户端】,所以小程序中的【网络请求】不是ajax 请求
javascript 复制代码
// 使用promise封装wx.request请求
pA () {
    return new Promise((resolve, reject) => {
      console.log('执行 A 接口的逻辑');
      wx.request({
        url: 'https://api.imooc-blog.lgdsunday.club/api/test/A',
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  }

// 使用async和await简化promise操作
async onPromiseGetClick () {
    const resA = await this.pA()
    console.log(resA.data.data.msg);
    const resB = await this.pB()
    console.log(resB.data.data.msg);
    const resC = await this.pC()
    console.log(resC.data.data.msg);
    const resD = await this.pD()
    console.log(resD.data.data.msg);
  }

生命周期

一件事件由创建到销毁的全过程

页面的生命周期

lua 复制代码
/ pages/list/list.js
Page({
	...
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log('onLoad');
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        console.log('onReady');
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        console.log('onShow');
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        console.log('onHide');
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        console.log('onUnload');
    },
	...
})

onLoad:最先被调用,可以用来接收别的页面传递过来的数据

onReady:页面初次渲染完成后调用,可以在这里从服务端获取数据

组件生命周期

组件的生命周期应该被定义在lifetimes中,而方法必须要放入到methods中

  1. created : 组件实例刚刚被创建好。此时还不能调用setData
  2. attached:组件完全初始化完毕、进入页面节点树后。绝大多数初始化工作可以在这个时机进行
  3. detached:在组件离开页面节点树后
scss 复制代码
/**
     * 组件的初始数据
     */
    data: {
        // 数据源
        listData: [],
        // 选中项
        active: -1
    },
	/**
     * 生命周期函数
     */
    lifetimes: {
        attached() {
            this.loadTabsData()
        }
    },
    /**
     * 组件的方法列表(组件中的方法必须定义到 methods 中)
     */
    methods: {
        /**
         * 获取数据的方法
         */
        loadTabsData() {
            wx.request({
                url: 'https://api.imooc-blog.lgdsunday.club/api/hot/tabs',
                success: (res) => {
                    this.setData({
                        listData: res.data.data.list,
                        active: 0
                    })
                }
            })
        }
    }
sql 复制代码
<scroll-view class="tabs-box" scroll-x>
    <view wx:for="{{ listData }}" wx:key="index" class="tab {{ active === index ? 'active' : '' }}">
        {{item.label}}
    </view>
</scroll-view>
css 复制代码
.tabs-box {
    /* 指定宽度 + 不换行 */
    width: 750rpx;
    white-space: nowrap;
    border-bottom: 1px solid #cccccc;
}

.tab {
    /* 指定 display */
    display: inline-block;
    padding: 12px 22px;
}

.active {
    color: #f94d2a;
}

数据列表分页展示

列表中数据过多时,一次性加载所有的数据会导致请求过慢,所以前端就会分页来加载数据

分页加载分为上拉加载和下拉刷新

kotlin 复制代码
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: async function () {
        console.log('onReachBottom');
        // 修改 page
        this.setData({
            page: this.data.page + 1
        })
         // 如果当前数据量已经 === 总数据量,则表示数据已经加载完成了,给用户一个提示,同时不在发送数据请求
        if (this.data.listData.length === this.data.total) {
             return;
        }
        // 获取最新数据
        const data = await this.getList()
        // 将最新的数据补充到现有数据的后面
        this.setData({
            listData: [...this.data.listData, ...data.list]
        })
    },

下拉刷新

想要在小程序中实现下拉刷新不同于上拉加载,需要首先开启下拉刷新

csharp 复制代码
// 页面.json
{
  "backgroundColor": "#cccccc",
  "enablePullDownRefresh": true
}

/**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: async function () {
        console.log('onPullDownRefresh');
        // 重置页数
        this.setData({
            page: 1
        })
         // 获取最新数据
         const data = await this.getList()
         // 将最新的数据补充到现有数据的后面
         this.setData({
             listData: data.list
         })
        //  关闭下拉刷新的动作(在真机中,下拉刷新动作不会自动关闭)
        wx.stopPullDownRefresh()
    },

页面跳转

  1. 声明式导航

    1. 跳转到 tabbar 页面
    2. 跳转到 非tabbar 页面
    3. 后退页面
  2. 编程式导航

    1. 跳转到 tabbar 页面
    2. 跳转到 非tabbar 页面
    3. 后退页面

声明式导航

小程序中提供了一个 跳转页面的组件navigator

xml 复制代码
<!-- 跳转到 非 tabbar 页面 -->
<block wx:for="{{ listData }}" wx:key="index">
        <view class="list-item">
            <!-- 注意:url 的表达式必须为 / 开头的页面路径 -->
            <navigator url="/pages/detail/detail">{{ index }} -- {{ item.title }}</navigator>
        </view>
    </block>

----

<!-- 跳转到 tabbar 页面 -->
<!-- 注意:跳转到 tabbar 页面,必须要指定 open-type="switchTab"-->
<navigator open-type="switchTab" url="/pages/index/index">跳转到首页</navigator>

-----

<!-- 后退页面 -->
<!-- 注意:后退页面必须指定 open-type="navigateBack" -->
<navigator open-type="navigateBack">后退</navigator>

编程式导航

xml 复制代码
// wx.switchTab:跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
<!-- 编程式导航跳转到首页 -->
<button type="primary" bindtap="onSwitchToHome">利用 switchTab 跳转到首页</button>
onSwitchToHome () {
    wx.switchTab({
        url: '/pages/index/index',
    })
}

// wx.navigateTo:保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面
<!-- 编程式导航跳转到详情页面 -->
<button type="primary" bindtap="onNavigateToDetail">利用 navigateTo 进入详情页</button>
onNavigateToDetail () {
    wx.navigateTo({
        url: '/pages/detail/detail',
    })
}

// wx.navigateBack:关闭当前页面,返回上一页面或多级页面
<!-- 编程式导航后退页面 -->
<button type="primary" bindtap="onNavigateBack">利用 navigateBack 后退页面</button>

onNavigateBack () {
    wx.navigateBack({
        delta: 1,
    })
}

导航传参

遵循get请求标准,以?分割url和参数,以=连接参数的key和value,以&来拼接参数

javascript 复制代码
// 声明式导航传递参数
<navigator url="/pages/detail/detail?index={{index}}&title={{item.title}}">{{ index }} -- {{ item.title }}</navigator>
// 编程式导航传递参数
<button type="primary" bindtap="onNavigateToDetail" data-index="{{index}}" data-title="{{item.title}}">利用 navigateTo 进入详情页</button>
onNavigateToDetail (e) {
    const { index, title } = e.target.dataset
    wx.navigateTo({
        url: `/pages/detail/detail?index=${index}&title=${title}`,
    })
}
// 在 detail 中接收数据,并展示
<view class="msg">index:{{index}} -- title:{{title}}</view>
onLoad: function (options) {
    const {index, title} = options;
    this.setData({
        index,
        title
    })
}
相关推荐
_.Switch24 分钟前
Python Web 架构设计与性能优化
开发语言·前端·数据库·后端·python·架构·log4j
libai27 分钟前
STM32 USB HOST CDC 驱动CH340
java·前端·stm32
程序员入门进阶35 分钟前
基于微信小程序的购物系统+php(lw+演示+源码+运行)
微信小程序·小程序·php
创意锦囊36 分钟前
网页与微信小程序:一场轻量化应用的博弈
微信小程序·小程序
程序员阿龙41 分钟前
计算机毕业设计之:基于微信小程序的校园流浪猫收养系统
微信小程序·小程序·课程设计·在线教育·教育管理系统·学习进度跟踪·教学平台
Java搬砖组长1 小时前
html外部链接css怎么引用
前端
GoppViper1 小时前
uniapp js修改数组某个下标以外的所有值
开发语言·前端·javascript·前端框架·uni-app·前端开发
丶白泽1 小时前
重修设计模式-结构型-适配器模式
前端·设计模式·适配器模式
程序员小羊!1 小时前
UI自动化测试(python)Web端4.0
前端·python·ui
破z晓1 小时前
OpenLayers 开源的Web GIS引擎 - 地图初始化
前端·开源