微信小程序开发04-1(小程序API)

1、路由_navigateTo

保留当前页面,跳转到应用内的某个页面。但是不能跳到 tabbar 页面。

温馨提示

程序中页面栈最多十层

页面跳转

可以从pageA页面通过点击事件跳转到pageB页面

javascript 复制代码
<view>PageA</view>
<button type="primary" bindtap="clickTapButton">跳转到PageB</button>
javascript 复制代码
Page({
  clickTapButton(e){
    wx.navigateTo({
     url: '/pages/pageB/pageB',
     })
   }
})

携带参数

javascript 复制代码
// pageA
Page({
  clickTapButton(e){
    wx.navigateTo({
     url: '/pages/pageB/pageB?name=itbaizhan',
     })
   }
})
javascript 复制代码
// pageB
Page({
  onLoad(options) {
    console.log(options.name);
   }
})

返回上一级页面

关闭当前页面,返回上一页面

css 复制代码
// pageB
Page({
  onLoad(options) {
    console.log(options.name);
   },
  backHandle() {
    wx.navigateBack({
      url:"/pages/pageA/pageA"
     })
   }
})

2、路由_redirectTo

关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面

redirectTo和navigateTo 最大的区别就是前者无法在返回之前的页面,也就是在页面栈中不存在之前的页面了

页面跳转

javascript 复制代码
<view>PageA</view>
<button type="primary" bindtap="clickTapButton">跳转到PageB</button>
javascript 复制代码
Page({
  clickTapButton(e){
    wx.redirectTo({
     url: '/pages/pageB/pageB?name=itbaizhan',
     })
   }
})

温馨提示

这里的参数携带依然是生效的!

3、路由_reLaunch

关闭所有页面,打开到应用内的某个页面

页面跳转

javascript 复制代码
// PageA
Page({
  clickTapButton(e){
    wx.navigateTo({
     url: '/pages/pageB/pageB?name=itbaizhan',
     })
   }
})
javascript 复制代码
// PageB
Page({
  onLoad(options) {
    console.log(options.name);
   },
  backHandle() {
    wx.reLaunch({
      url:"/pages/pageC/pageC"
     })
   }
})

4、路由_switchTab

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

实现tabbar

javascript 复制代码
"tabBar": {
  "color": "#bfbfbf",
  "selectedColor": "#d81e06",
  "backgroundColor": "#fff",
  "borderStyle": "black",
  "position": "bottom",
  "list": [{
    "pagePath": "pages/pageA/pageA",
    "text": "首页",
    "iconPath": "./images/home.png",
    "selectedIconPath": "./images/home_select.png"
   },
       {
         "pagePath": "pages/pageB/pageB",
         "text": "新闻",
         "iconPath": "./images/news.png",
         "selectedIconPath": "./images/news_select.png"
       }
   ]
}

温馨提示

由于之前详细讲解过tabbar,这里就不展开代码,大家可以参考之前的代码

页面跳转

javascript 复制代码
// home
Page({
  clickHandle(){
    wx.switchTab({
     url: '/pages/pageA/pageA',
     })
   }
})

5、交互_消息提示框

显示消息提示框,给出用户提示,注意该提示框是无焦点的

基本弹出框

javascript 复制代码
<button type="primary" bindtap="clickToastHandle">弹出提示框</button>
javascript 复制代码
Page({
  onLoad(options) {},
  clickToastHandle(){
    wx.showToast({
      title: '成功',
      icon: 'success',
      duration: 2000
     })
   }
})

常用属性

属性 类型 默认值 必填 说明
title string 提示的内容
icon string success 图标
image string 自定义图标的本地路径,image 的优先级高于 icon
duration number 1500 提示的延迟时间
mask boolean false 是否显示透明蒙层,防止触摸穿透

icon详情

合法值 说明
success 显示成功图标,此时 title 文本最多显示 7 个汉字长度
error 显示失败图标,此时 title 文本最多显示 7 个汉字长度
loading 显示加载图标,此时 title 文本最多显示 7 个汉字长度
none 不显示图标,此时 title 文本最多可显示两行
javascript 复制代码
Page({
  onLoad(options) {},
  clickToastHandle(){
    wx.showToast({
      title: '等待数据加载',
      icon: 'loading',
      duration: 2000,
      mask:true,
      image:"../../images/loading.png"
     })
   }
})

hideToast

隐藏消息提示框

javascript 复制代码
Page({
  onLoad(options) {},
  clickToastHandle(){
    wx.showToast({
      title: '等待数据加载',
      icon: 'loading',
      duration: 5000,
      mask:false,
      image:"../../images/loading.png"
     })
   },
  clickHideToast(){
    wx.hideToast()
   }
})

6、交互_ loading 提示框

显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框

基本实现

javascript 复制代码
Page({
  onLoad(options) {
    wx.showLoading({
      title: '加载中'
     })
   }
})

常用属性

属性 类型 默认值 必填 说明
title string 提示的内容
mask boolean false 是否显示透明蒙层,防止触摸穿透
javascript 复制代码
Page({
  onLoad(options) {
    wx.showLoading({
      title: '加载中',
      mask:true
     })

    setTimeout(() =>{
      wx.hideLoading()
     },2000)
   }
})

7、交互_模态对话框

显示模态对话框,其实就是可以进行交互了

基本对话框

javascript 复制代码
<button type="primary" bindtap="clickModalHandle">显示对话框</button>
javascript 复制代码
Page({
  clickModalHandle(){
    wx.showModal({
      title: '提示',
      content: '这是一个模态弹窗',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
         } else if (res.cancel) {
          console.log('用户点击取消')
         }
       }
     })
   }
})

常用属性

属性 类型 默认值 必填 说明
title string 提示的标题
content string 提示的内容
showCancel boolean true 是否显示取消按钮
cancelText string 取消 取消按钮的文字,最多 4 个字符
cancelColor string #000000 取消按钮的文字颜色,必须是 16 进制格式的颜色字符串
confirmText string 确定 确认按钮的文字,最多 4 个字符
confirmColor string #576B95 确认按钮的文字颜色,必须是 16 进制格式的颜色字符串
editable boolean false 是否显示输入框
placeholderText string 显示输入框时的提示文本

存在输入框

object.success 回调函数

属性 类型 说明
content string editable 为 true 时,用户输入的文本
confirm boolean 为 true 时,表示用户点击了确定按钮
cancel boolean 为 true 时,表示用户点击了取消
javascript 复制代码
Page({
  clickModalHandle(){
    wx.showModal({
      title: '提示',
      // content: '这是一个模态弹窗',
      showCancel:true,
      cancelText:"残忍拒绝",
      cancelColor:"#ff0000",
      confirmText:"欣然接受",
      confirmColor:"#00ff00",
      editable:true,
      placeholderText:"请输入信息",
      success(res) {
        if (res.confirm) {
          // res.content获取用户输入信息
          console.log('用户点击确定',res.content)
         } else if (res.cancel) {
          console.log('用户点击取消')
         }
       }
     })
   }
})

8、交互_操作菜单

显示操作菜单,菜单会从底部弹出

基本实现

javascript 复制代码
<button type="primary" bindtap="clickActionSheetHandle">显示底部菜单栏</button>
javascript 复制代码
Page({
  clickActionSheetHandle() {
    wx.showActionSheet({
      itemList: ['A', 'B', 'C'],
      success(res) {
        console.log(res.tapIndex)
       },
      fail(res) {
        console.log(res.errMsg)
       }
     })
   }
})

常用属性

属性 类型 默认值 必填 说明
itemList Array. 按钮的文字数组,数组长度最大为 6
itemColor string #000000 按钮的文字颜色
success function 接口调用成功的回调函数
fail function 接口调用失败的回调函数

获取数据

object.success 回调函数

属性 类型 说明
tapIndex number 用户点击的按钮序号,从上到下的顺序,从0开始
javascript 复制代码
Page({
  data:{
    citys:["北京","西安","太原","河北","内蒙"]
   },
  clickActionSheetHandle() {
    var that = this;
    wx.showActionSheet({
      itemList: this.data.citys,
      itemColor:"#f00",
      success(res) {
        console.log(that.data.citys[res.tapIndex])
       },
      fail(res) {
        console.log(res.errMsg)
       }
     })
   }
})

9、动态设置导航栏

在微信小程序中,我们可以通过逻辑动态设置导航栏

常用设置

方法 描述
showNavigationBarLoading 在当前页面显示导航条加载动画
hideNavigationBarLoading 在当前页面隐藏导航条加载动画
setNavigationBarTitle 动态设置当前页面的标题
hideHomeButton 隐藏返回首页按钮。当用户打开的小程序最底层页面是非首页时,默认展示"返回首页"按钮,开发者可在页面 onShow 中调用 hideHomeButton 进行隐藏
javascript 复制代码
<button type="primary" bindtap="bindShowBarHandle">显示加载动画</button>
<button type="primary" bindtap="bindHideBarHandle">隐藏加载动画</button>
<button type="primary" bindtap="bindSetBarTitle">设置导航条文本</button>
javascript 复制代码
Page({
  bindShowBarHandle(){
    wx.showNavigationBarLoading();
   },
  bindHideBarHandle(){
    wx.hideNavigationBarLoading();
   },
  bindSetBarTitle(){
    wx.setNavigationBarTitle({
      title: '当前页面'
     })
   },
  onShow(){
    wx.hideHomeButton()
   }
})

10、网络请求

网络请求

发起 HTTPS 网络请求,从后端获取数据,显示在页面之上

基本使用

通过wx.request请求数据

javascript 复制代码
Page({
  onLoad(options) {
    wx.request({
      url: 'https://iwenwiki.com/api/blueberrypai/getChengpinDetails.php',
      success(res) {
        console.log(res.data)
       }
     })
   }
})

温馨提示

在小程序中使用网络相关的 API 时,需要注意下列问题,请开发者提前了解

每个微信小程序需要事先设置通讯域名,小程序只可以跟指定的域名进行网络通信(生产环境)

通过开发者工具配置:"不效验合法域名" (开发环境)

生产环境

服务器域名请在 「小程序后台 - 开发 - 开发设置 - 服务器域名」 中进行配置

开发环境

小程序开发者工具:详情 - 本地设置 - 勾选 "不效验合法域名" 选项

javascript 复制代码
<view>
  <block wx:for="{{ chengpinDetails }}" wx:key="index">
    <text>{{ item.title }}</text>
  </block>
</view>
javascript 复制代码
Page({
  data:{
    chengpinDetails:[]
   },
  onLoad(options) {
    var that = this;
    wx.request({
      url: 'https://iwenwiki.com/api/blueberrypai/getChengpinDetails.php',
      success(res) {
        that.adapterView(res)
       }
     })
   },
  adapterView(res){
    this.setData({
      chengpinDetails:res.data.chengpinDetails
     })
   }
})

11、网络请求_常用参数

我们了解了基本的网络请求之后,在考虑在网络请求中的属性如何使用。例如:如何传递参数?

常用属性

属性 类型 默认值 必填 说明
url string 开发者服务器接口地址
data string/object/ArrayBuffer 请求的参数
header Object 设置请求的 header,header 中不能设置 Referer。 content-type 默认为 application/json
timeout number 超时时间,单位为毫秒。默认值为 60000
method string GET HTTP 请求方法 常用的方式 GET和POST
success function 接口调用成功的回调函数
fail function 接口调用失败的回调函数
complete function 接口调用结束的回调函数(调用成功、失败都会执行)
javascript 复制代码
Page({
  data: {
    chengpinDetails: []
   },
  onLoad(options) {
    wx.request({
      url: 'http://iwenwiki.com:3002/api/foods/list',
      method: "GET",
      data: {
        city: "北京"
       },
      header: {
        'content-type': 'application/json'
       },
      timeout:5000,
      success(res) {
        console.log(res.data);
       },
      fail(error){
        console.log(error);
       },
      complete(){
        console.log("网络请求完成");
       }
     })
   }
})

12、封装网络请求

封装网路请求是为了日后使用更加方便

javascript 复制代码
/**
 * 
 * @param { string } url 
 * @param { string/object/ArrayBuffer } params 
 * @param { GET|POST } method 
 */
function request(url, params, method) {
  wx.showLoading({
    title: '加载中...',
    mask: true
   })

  let promise = new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: params,
      header: {
        'content-type': 'application/json'
       },
      method: method,
      success: res => {
        resolve(res.data)
       },
      fail: err => {
        reject(err)
       },
      complete: () => {
        wx.hideLoading();
       }
     })
   })
  return promise;
}

module.exports = {
  request
}
javascript 复制代码
const { request } = require("../../utils/request.js")
Page({
  data: {
    result: []
   },
  onLoad(options) {
    request("http://iwenwiki.com:3002/api/foods/list",{city:"北京"},"GET")
     .then(res =>{
      console.log(res.data);
      this.setData({
        result:res.data.result
       })
     })
   }
})
javascript 复制代码
<view>
  <block wx:for="{{ result }}" wx:key="index">
    <view>{{ item.name }}</view>
  </block>
</view>

13、下拉刷新

下拉刷新是我们在移动端所见的最多效果,所有用户希望看到的最新数据的解决方案基本上都会选择"下拉刷新"方式实现。例如:微信的朋友圈

实现下拉刷新的四步
第一步:json 文件配置下拉刷新

javascript 复制代码
{
  "enablePullDownRefresh": true,
  "backgroundColor": "#f1f1f1",
  "backgroundTextStyle":"dark"
}

第二步:实现下拉刷新逻辑

javascript 复制代码
Page({
  data: {
    list:[1,2,3,4,5]
   },
  onPullDownRefresh() {
    setTimeout(() =>{
      this.setData({
        list:[6,7,8,9,10]
       })
      wx.stopPullDownRefresh();
     },1000)
   }
})

第三步:渲染视图

javascript 复制代码
<view class="root">
  <view wx:for="{{ list }}" wx:key="index">
    <view class="item">{{ item }}</view>
  </view>
</view>

第四步:设计样式

javascript 复制代码
page{
  background: #fff;
}
.root{
  padding: 10px;
}
.item{
  width: 100%;
  height: 50px;
  border-bottom: 1px solid #afafaf;
  line-height: 50px;
}

14、下拉刷新应用

掌握了基础的下拉刷新之后,我们要做的就是真实的应用场景,我们通过网络请求获取数据,并渲染到页面上

json 文件配置

javascript 复制代码
{
  "enablePullDownRefresh": true,
  "backgroundColor": "#f1f1f1",
  "backgroundTextStyle":"dark"
}

逻辑文件

javascript 复制代码
const { request } = require("../../utils/request.js")
Page({
  data: {
    list:[],
    page:1
   },
  onLoad(options){
    this.http(this.data.page)
   },
  onPullDownRefresh() {
    this.setData({
      page:this.data.page+=1
     })
    this.http(this.data.page)
   },
  http(page){
    request("http://iwenwiki.com:3002/api/foods/list","GET",{
      city:"北京",
      page:page
     }).then(res =>{
      if(!res.msg){
        this.setData({
          list:res.data.result
         })
       }else{
        wx.showToast({
         title: res.msg,
         })
       }
      wx.stopPullDownRefresh()
     })
   }
})

页面渲染

javascript 复制代码
<view class="root">
  <view class="item" wx:for="{{ list }}" wx:key="index">
    <image src="{{ item.pic }}"></image>
    <text>{{ item.name }}</text>
  </view>
</view>

样式文件

javascript 复制代码
page{
  background: #f1f1f1;
}

.root{
  padding: 10px;
}

.item{
  height: 80px;
  margin: 5px 0;
  background: #fff;
  line-height: 100px;
  padding: 10px;
}

image{
  width: 80px;
  height: 80px;
}

text{
  height: 80px;
  padding-left: 10px;
  position: absolute;
  line-height: 80px;
}

14、上拉加载

"下拉刷新"是为了更新数据,"上拉加载"是为了增加数据,也是页面最常见的效果。例如:微信朋友圈

实现上拉加载的四步
第一步:json 文件配置(可选项)

javascript 复制代码
{
  "onReachBottomDistance":50
}

第二步:实现上拉加载逻辑

javascript 复制代码
Page({
  data: {
    list:[1,2,3,4,5]
   },
  onReachBottom() {
    this.setData({
      list:this.data.list.concat([6,7,8,9,10])
     })
   }
})

第三步:渲染页面

javascript 复制代码
<view class="container">
  <view class="item" wx:for="{{ list }}" wx:key="index">
    <text>{{ item }}</text>
  </view>
</view>

第四步:样式加载

javascript 复制代码
.item{
  height: 200px;
}
text{
  font-size: 30px;
}

15、上拉加载应用

掌握了基础的上拉加载之后,我们要做的就是真实的应用场景,我们通过网络请求获取数据,并渲染到页面上

json 文件配置

javascript 复制代码
{
  "onReachBottomDistance":50
}

逻辑文件

javascript 复制代码
const { request } = require("../../utils/request.js")

Page({
  data: {
    list:[],
    page:1
   },
  onLoad(options) {
    this.http(this.data.page);
   },
  onReachBottom() {
    this.setData({
      page:this.data.page+=1
     })
    this.http(this.data.page)
   },
  http(page){
    request("http://iwenwiki.com:3002/api/foods/list","GET",{
      city:"北京",
      page:page
     }).then(res =>{
      if(!res.msg){
        this.setData({
          list:this.data.list.concat(res.data.result)
         })
       }else{
        wx.showToast({
         title: res.msg,
         })
       }
     })
   }
})

页面渲染

javascript 复制代码
<view class="root">
  <view class="item" wx:for="{{ list }}" wx:key="index">
    <image src="{{ item.pic }}"></image>
    <text>{{ item.name }}</text>
  </view>
</view>

样式文件

javascript 复制代码
page{
  background: #f1f1f1;
}

.root{
  padding: 10px;
}

.item{
  height: 80px;
  margin: 5px 0;
  background: #fff;
  line-height: 100px;
  padding: 10px;
}

image{
  width: 80px;
  height: 80px;
}

text{
  height: 80px;
  padding-left: 10px;
  position: absolute;
  line-height: 80px;
}
相关推荐
说私域2 小时前
AI智能名片S2B2C商城小程序在微商中的应用与影响
大数据·人工智能·小程序·流量运营
苏苏哇哈哈3 小时前
微信小程序实现高性能动态配置水滴凹槽、凸起Tabbar 组件
微信小程序·小程序
逆龙泰氽3 小时前
微信小程序开发03(WXML语法)
微信小程序·小程序
2501_916007473 小时前
iOS APP 开发,从项目创建、证书与描述文件配置、安装测试和IPA 上传
android·ios·小程序·https·uni-app·iphone·webview
CHU7290353 小时前
淘宝扭蛋机小程序前端功能详解:以交互设计赋能趣味体验
java·前端·小程序·php
CHU7290351 天前
安心陪伴,便捷就医:陪诊代办小程序的温暖设计
前端·小程序·php
CHU7290351 天前
线上扭蛋机拆盒小程序前端功能版块解析
前端·小程序·php
深海蓝山1 天前
基于Canvas的原生签名组件,兼容小程序和H5
小程序·canvas·签名
毕设源码-邱学长1 天前
【开题答辩全过程】以 基于微信小程序的课程表信息系统的开发实现为例,包含答辩的问题和答案
微信小程序·小程序