Summary of WeChat Mini Programs

Global configuration file

pages

  • How many pages does the WeChat mini program have?

window

  • The head of the mini program, used to set the status bar, navigation bar, title, and window background color of the mini program

  • backgroundTextStyle

    • The style of drop-down loading, the values ​​are light(highlight), and dark(dark)
  • navigationBarBackgroundColor

    • Header navigation background color
  • navigationBarTitleText

    • Header navigation title
    • Subpages can modify their own header titles through navigationBarTitleText
  • navigationBarTextStyle

    • Header navigation title style

tabBar

  • Bottom navigation bar
    • selectedColorThe color of the text on the tab when it is selected. Only hexadecimal colors are supported.
"tabBar": {
    
    
  // tab 上的文字选中时的颜色,仅支持十六进制颜色
  "selectedColor": "#269fde",
  "list": [{
    
    
    "pagePath": "pages/index/index",
    "text": "首页",
    // 默认图标
    "iconPath": "/images/home.png",
    // 选中时的图标
    "selectedIconPath": "/images/home-o.png"
  }, {
    
    
    "pagePath": "pages/my/my",
    "text": "我的",
    "iconPath": "/images/my.png",
    "selectedIconPath": "/images/my-o.png"
  }]
}

wxml

  • view is equivalent to div

  • image is equivalent to img

  • The input input box cannot be seen when it has no style.

  • button button

  • text is equivalent to span

wxss

  • rpx is equivalent to rem and will adapt to the mobile phone screen

flex layout

  • Change spindle direction: text-direction
  • Line wrap: flex-wrap: wrap
  • Spindle Alignment
    • justify-content
    • felx-start flex-end space-between space-around
  • cross axis alignment
    • align-items

event

  • bindtap is the binding event (click)

Get the content in the input box

  • Get the content in the input box through bindinput (triggered as long as the content changes)
  • Get the content in the input box through bindchange (triggered when the content changes and the cursor leaves)
  • By receiving events,e.detail.value

data binding

  • Define initial data in js data, and then render it into wxml through { {}}

One-way data binding

  • This.old value = new value should not be used
  • You should use this.setDate({ variable name: new value})
turn() {
    
    
    // this.data.pindao = '少儿频道'
    // console.log(this.data.pindao);
    this.setData({
    
    
      pindao: '少儿频道'
	})
}

Two-way data binding

  • Generally used for form types
  • First bindinputget the value in the input box through
  • Then render the old value into the new value through setData({ old value: e.detail.value })
wxml
<view>{
    
    {
    
    danmu}}</view>
<input bindinput="get" class="danmu" type="text" placeholder="请出入内容"/>

js
get(e) {
    
    
  console.log(e.detail.value);
  this.setData({
    
    
    danmu: e.detail.value
  })
}

Commonly used APIs

  • wx.begins

Pop-ups

  • wx.showToast()
submit() {
    
    
  wx.showToast({
    
    
    title: '提交失败',
    icon: 'error',
    duration: 3000
  })
}

Page jump

  • wx.navigateTo() cannot jump to the tabBar (bottom navigation) and retains the current page
wxml
<button bindtap="toaaa" class="btn">toaaa</button>

js
toaaa() {
    
    
  wx.navigateTo({
    
    
    url: '/pages/aaa/aaa',
  })
}
  • wx.redirectTo() does not retain the current page. The difference from wx.navigateTo is: redirectTo returns and jumps to the previous page (because the current page is not retained)
wxml
<button bindtap="toBBB">tobbb</button>

js
toBBB() {
    
    
  wx.redirectTo({
    
    
    url: '/pages/bbb/bbb',
  })
}
  • wx.switchTab() can only jump to tabBar
wxml
<button bindtap="todata">todata</button>

js
todata() {
    
    
  wx.switchTab({
    
    
    url: '/pages/data/data',
  })
}
  • wx.navigateBack() Jump to previous pages
wxml
<button bindtap="reback">返回到上一个页面上</button>

js
reback() {
    
    
  wx.navigateBack({
    
    
    delta: 1
  })
}
// 也可以不写delta,省略就是返回上一页
  • wx.reLaunch() closes all pages and opens to a page within the application
wxml
<button bindtap="openPage">关闭所有页面,打开到应用内的某个页面</button>

js
openPage() {
    
    
    wx.reLaunch({
    
    
        url: '/pages/data/data',
    })
}
  • Request call interface

  • wx.request() initiates an HTTPS network request or imports (utils)

  • Use the old version of the function form to write, pay attention to the problem of this pointing, but this will not happen with arrow functions (this does not point to the upper level scope)

let that = this
wx.request({
    
    
  url: 'https://cnodejs.org/api/v1/topics',
  // 用老版本的函数形式写,注意有this指向的问题,但是用箭头函数就不会了
  success(res) {
    
    
    // console.log(res)
    // Cannot read property 'setData' of undefined   找不到this
    that.setData({
    
    
      dataList: res.data.data
    })
  }
})

Obtain WeChat authorized user information

  • wx.getUserProfile
    • res.userInfo.nickName gets the user name
    • res.userInfo.avatarUrl Get the user avatar address
wxml
<button bindtap="getUserInfo">获取用户信息</button>

js
getUserInfo() {
    
    
  wx.getUserProfile({
    
    
    desc: '用于完善个人信息',
    success(res) {
    
    
      console.log(res);
      // 获取用户名
      console.log(res.userInfo.nickName);
      // 获取用户头像地址
      console.log(res.userInfo.avatarUrl);
    }
  })
}
  • TypeError: Cannot read property 'setData' of undefined Classic error, this points to something wrong
getUserInfo() {
    
    
  // 这里需要把this转存到that中,this指的是page
  let that = this
  wx.getUserProfile({
    
    
    desc: '用于完善个人信息',
    success(res) {
    
    
      console.log(res);
      // 获取用户名
      console.log(res.userInfo.nickName);
      // 获取用户头像地址
      console.log(res.userInfo.avatarUrl);
      // 这里的this指的是sucess,不是page
      that.setData({
    
    
        userName: res.userInfo.nickName,
        avatarUrl: res.userInfo.avatarUrl
      })
    }
  })
}

Global globalData data

  • Global data is defined in globalData in app.js

  • Components need to instantiate global data before they can call global data in globalData.

const app = getApp()

Set user data as global data

  1. First, cache it into globalData
getUserInfo() {
    
    
  // 这里需要把this转存到that中,this指的是page
  let that = this
  wx.getUserProfile({
    
    
    desc: '用于完善个人信息',
    success(res) {
    
    
      console.log(res);
      // 获取用户名
      console.log(res.userInfo.nickName);
      // 获取用户头像地址
      console.log(res.userInfo.avatarUrl);
      // 这里的this指的是sucess,不是page
      that.setData({
    
    
        userName: res.userInfo.nickName,
        avatarUrl: res.userInfo.avatarUrl
      })

      // 获取到用户信息后,转存到全局数据中
      app.globalData.userInfo = res.userInfo
    }
  })
}
  1. You can use the following page
clickItem() {
    
    
  console.log('被点击了');
  console.log(app.globalData.userInfo);
}

local storage

set up

  • wx.setStorageSync(‘key’,value)

Obtain

  • wx.getStorageSync(‘key’)

  • First, user information must be transferred to global data.

  • Then the user data must be stored in the local cache (this is convenient for other pages to obtain directly through local data)

    • As long as it is cached in the local cache, there is data. Even if you refresh, as long as you don't close the page, there will still be data.
    • Then it is a one-time authorization to obtain user information, and other pages can be used directly by obtaining the local cache and transferring it to global data.
授权获取
getUserInfo() {
    
    
  let that = this
  wx.getUserProfile({
    
    
    desc: '完善信息',
    success(res) {
    
    
      // console.log(res);
      // 获取用户名及头像地址
      console.log(res.userInfo.nickName);
      console.log(res.userInfo.avatarUrl);
      that.setData({
    
    
        nickName: res.userInfo.nickName,
        avatarUrl: res.userInfo.avatarUrl
      })
      // 将用户信息存储为全局数据
      app.globalData.userInfo = res.userInfo
      // 获取后存储本地
      wx.setStorageSync('userInfo', res.userInfo)
    }
  })
}

其他页面使用
show() {
    
    
  // 获取缓存中的数据
  wx.getStorageSync('userInfo')
  // 把缓存获取到的数据转存给全局变量app.globalData.userInfo
  app.globalData.userInfo = wx.getStorageSync('userInfo')

  this.setData({
    
    
    userInfo: app.globalData.userInfo
  })
}

life cycle

  • Divided into two categories, one is the page life cycle and the other is the application life cycle.

Page life cycle

  • Just each page individually

    1. onLoad monitors the loading of the current page and will only execute it once
      • Generally make a data request and obtain the passed parameters (with an options parameter by default)
    onLoad(options) {
          
          
        console.log('onLoad声明周期,只会执行一次,一般做初始请求用',options)
    },
    
    1. onReady (triggered when the initial rendering of the page is completed. It will only be called once for a page)

      • Make more modifications to use
    2. onShow (as long as this page is displayed, it will be loaded automatically), displayed once, loaded once

      • Do more page data updates
    3. onHide (automatically loaded every time the page is hidden), hidden once, loaded once

    4. onUnload (unload page, close applet)

// pages/alive/alive.js
Page({
    
    
  /**
   * 页面的初始数据
   */
  data: {
    
    

  },

  /**
   * 生命周期函数--监听页面加载,只会执行一次(only one)
   * options 形参接收上个页面传递过来的参数
   */
  onLoad(options) {
    
    
    console.log('onLoad声明周期,只会执行一次,一般做初始请求用',options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成,一个页面只会调用一次
   */
  onReady() {
    
    
    console.log('onReady声明周期,多做修改内容使用')
  },

  /**
   * 生命周期函数--监听页面显示,显示一次,加载一次,多做数据更新用
   */
  onShow() {
    
    
    console.log('onShow显示一次,加载一次,多做数据更新用')
  },

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

  /**
   * 生命周期函数--监听页面卸载, (卸载页面,小程序关闭时触发)
   */
  onUnload() {
    
    
    console.log('onUnload小程序关闭时触发');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    
    

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    
    

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    
    
      
  }
})

Application life cycle

  • That is, the entire WeChat applet application is written in app.js
    1. onLaunch is triggered when the mini program initialization is completed, and will only be triggered once globally.
      • Generally used to obtain user information
    2. onShow (triggered when the applet is started, or when it enters the foreground display from the background)
    3. onHide (triggered when the applet enters the background from the foreground)
App({
    
    
  // 小程序初始化完成时触发,全局只会触发一次。一般用于获取用户的信息
  onLaunch() {
    
    
    console.log('onLaunch 小程序初始化完成时触发,全局只会触发一次,一般获取用户信息用')
  },
  // 小程序启动,或从后台进入前台显示时触发
  onShow() {
    
    
    console.log('onShow 小程序启动,或从后台进入前台显示时触发')
  },
  // 小程序从前台进入后台时触发
  onHide() {
    
    
    console.log('onHide 小程序从前台进入后台时触发')
  },
  // 全局数据  globalData
  globalData: {
    
    
    userInfo: null
  }
})

type of data

  • number、string、boolean、null、undefined、Object ( Function、Array、Date . . . )
simple data type describe
number Numeric type, including integers and decimals, such as 18, 18.8
string String type, such as "华神". Note that strings in js must be quoted.
boolean Boolean value type, there are two values: true and false, representing true and false
undefined Undefined This value means that the variable does not contain a value, such as var a; if the variable a is declared but has no value assigned, it is undefined.
null Null value, such as var a=null, declares variable a to be null
object Object types: Function, Array, Date . . .

Data type conversion

  • Convert to string
Way illustrate Case
toString() Convert to string var age=1 age.toString()
String() Convert to string var age=1 String(age)
Concatenate strings with plus sign Convert to string var age=1 “”+age
  • Convert to numeric type
Way illustrate Case
Number() Convert string to number Number("8.88") // Return 8.88
pressFloat() Parses a string and returns a float parseFloat("8.88") //Return 8.88
parseInt() Parses a string and returns an integer parseInt("8.88") //Return 8.88

Several special cases of converting to numbers

console.log(Number(""))//空字符串转换为 0
console.log(Number(true))//true转换为1
console.log(Number(false))//false转换为0
console.log(Number("华神"))//其他的字符串会转换为 NaN (因为转换过来不是数字)

array

  • let arr = […]

  • let arr = new Array()

    • If there is only one parameter, it is the length
    • If there are 2 or more, it is an array element
  • Arrays can contain different variables

Add element

  • Add push at the end and return the length of the new array
  • Add unshift to the head and return the length of the new array

Delete element

  • Delete pop at the end and return the deleted element

  • Delete shift in the head and return the deleted element

  • splice (start from the number, delete a few)

  • splice(start from which number, how many to replace, the value to be replaced)

car.splice(0,2,'红旗','特斯拉')
console.log(car)

Merge arrays

  • concat combines multiple arrays and is mostly used for drop-down loading (splicing)
console.log(car.concat(home))

List rendering

  • wx: for
  • The block tag is generally used for looping or judgment (equivalent to the template tag)

render array

<view wx:for="{
    
    {carList}}" wx:key="index">
  {
    
    {
    
    index + 1}} -- {
    
    {
    
    item}}
</view>

<block wx:for="{
    
    {carList}}" wx:key="index">
  <view>{
    
    {
    
    index + 1}} -- {
    
    {
    
    item}}</view>
</block>

render object

<block wx:for="{
    
    {userList}}" wx:key="index">
  <view>{
    
    {
    
    item.name}}</view>
  <view>{
    
    {
    
    item.age}}</view>
  <view>{
    
    {
    
    item.sex}}</view>
</block>

<block wx:for="{
    
    {userList}}" wx:key="index">
  <view>{
    
    {
    
    item.name}} || {
    
    {
    
    item.age}} || {
    
    {
    
    item.sex}}</view>
</block>

Conditional rendering

  • wx: if can be combined with vx:elif and wx:else
<view wx:if="{
    
    {false}}">是否显示呢</view>
// 根据条件判断
<view wx:if="{
    
    {flag}}">是否显示呢</view>
<view wx:if="{
    
    {!flag}}">是否显示呢</view>

<view wx:if="{
    
    {num == 1}}">1</view>
<view wx:elif="{
    
    {num == 2}}">2</view>
<view wx:else>3</view>

Math

random number

  • Math.random() [0,1)

  • Generate random decimals between min - max

let min = 10
let max = 100
console.log(Math.random() * (max - min ) + min)
  • Generate a random integer between min - max
let min = 10
let max = 100
console.log(Math.floor(Math.random() * (max - min ) + min))
  • Get a random integer between two numbers (greater than or equal to min, less than max)
// 这个随机数是min和max之间的随机整数
function getRandomInt(min, max) {
    
    
  min = Math.ceil(min)
  max = Math.floor(max)
  //不含最大值,含最小值
  return Math.floor(Math.random() * (max - min)) + min;
}
  • Get a random integer between two numbers (greater than or equal to min, less than or equal to max)
// 这个随机数是min和max之间的随机整数
function getRandomInt(min, max) {
    
    
  min = Math.ceil(min)
  max = Math.floor(max)
  //含最大值,含最小值 
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

Date

  • Date is a constructor and must be instantiated before it can be used
let date = new Date()
console.log(date)   // 会输出当前的时间
  • require('…') import (common.js specification)
let utils = require('../../utils/util.js')
  • Format time
let utils = require('../../utils/util.js')

let nowTime = utils.formatTime(time)
console.log(nowTime)
this.setData({
    
    
  nowTime
})
  • Pass in parameters
let utils = require('../../utils/util.js')

let date = new Date('2022-2-25 12:00:00')
console.log(date)
let time = new Date(1645796691081)
console.log(utils.formatTime(time))
  • Get timestamp
let time = new Date()
console.log(time.getTime())
let date = +new Date()
console.log(date)
let d = Date.now()
console.log(d)
  • Common operations
method describe
getFullYear() Get the four-digit year (yyyy)
getMonth() Get month (0-11) Remember +1
getDate() Returns the day as a numerical value (1-31)
getHours() Get the hour (0-23)
getMinutes() Get points (0-59)
getSeconds() Get seconds (0-59)
getDay() Get the week name as a numerical value (0-6)
getMilliseconds() Get milliseconds (0-999)
getTime() Get timestamp (from January 1, 1970 to present)

this

  • In the first-level function, this points to the page instantiation
    • The variables set by this.setDate are directly saved to the page instantiation and can be directly rendered and used in wxml.
onLoad() {
    
    
    console.log(this)
    this.setDate({
    
    
        cat: '花花'
    })
}
  • The inner function points to the inner function itself. If you need to use this, you need to dump this
let that = this
wx.request({
    
    
  url: 'https://www.baidu.com',
  success(res) {
    
    
    console.log(res);
    let aaa = 3
    // Cannot read property 'setData' of undefined   找不到this
    that.setData({
    
    
      dataVal: aaa
    })
  }
})

Callback

  • Asynchronous operation functions in JavaScript often use callback functions to process the results of asynchronous tasks.

  • The callback function is a function that tells it when we start an asynchronous task: what to do after you complete the task. In this way, the main thread hardly needs to care about the status of the asynchronous task, and it will start and end by itself.

arrow function

  • The arrow function itself does not have this pointed to, it depends on the context
    • If an arrow function is used here, there is no need to declare that.
wx.request({
    
    
  url: 'https://www.baidu.com',
  success:(res)=> {
    
    
    console.log(res);
    let aaa = 3
    // Cannot read property 'setData' of undefined   找不到this
    this.setData({
    
    
      dataVal: aaa
    })
  }
})

Promise style

  • Can only be used for cloud development
  • wx.clode.database().collection('database table name').get() gets the database table and makes a request
wx.cloud.database().collection('数据库表名称').get()
.then(res=>{
    
    
    this.setData({
    
    
        
    })
    this.coding()
})

Application scenarios

  • When multiple asynchronous operations need to be performed sequentially
    • eg: If you want to detect the username and password successively through the asynchronous method, you need to detect the username asynchronously first, and then detect the password asynchronously. It’s very suitable for Promise

navigator

  • navigator cannot jump to tabBar
<navigator url="/pages/page01/page01">page01</navigator>
  • Equivalent to a link label jump + carrying parameters. The biggest difference between this and programmatic navigation is that parameters can be passed
      1. Pass parameters: After the hash address? Parameter name = { { object name.xxx }}
<navigator class="aa" url="/pages/page01/page01?id={
    
    {zs.id}}&name={
    
    {zs.name}}">{
    
    {
    
    zs.name}}</navigator>
      1. The received parameter is a large object that can only be received in onLoad.
onLoad: function (options) {
    
    
  console.log(options);    // page01.js:15 {id: "1", name: "张三"}
}

Api jump carries parameters

Jump method illustrate Corresponding to wx method
navigate Keep the current page and jump to a page within the app. But cannot jump to the tabbar page wx.navigateTo
redirect Close the current page and jump to a page within the app. But it is not allowed to jump to the tabbar page wx.redirectTo
switchTab Jump to the tabBar page and close all other non-tabBar pages wx.switchTab
reLaunch Close all pages and open to a page within the app wx.reLaunch
navigateBack Close the current page and return to the previous page or multi-level page wx.navigateBack
exit Exit the mini program, effective when target="miniProgram" none
    1. Pass parameters
toPage02() {
    
    
  wx.navigateTo({
    
    
    url: '/pages/page02/page02?id=' + this.data.zs.id + '&name=' + this.data.zs.name,
  })
}
    1. Receive parameters can only be received in onLoad
onLoad: function (options) {
    
    
  console.log(options);
  console.log(options.id);
  console.log(options.name);
},

Guess you like

Origin blog.csdn.net/qq_52845451/article/details/126934153