1. Network request API and encapsulation wx.request (Object object)
RequestTask | WeChat Open Documentation
1.1 API parameters
1.2 API usage
1.3 Network request--API encapsulation
- Wrap it into a function using a promise
export function MyRequest(options) { return new Promise((resolve, reject) => { wx.request({ ...options, success: (res) => { resolve(res.data) }, fail: reject }) }) }
- Encapsulate into a class, and then instantiate (encapsulate baseURL, get, post
class MyRequest { constructor(baseURL) { this.baseURL = baseURL } request(options) { const { url } = options return new Promise((resolve, reject) => { wx.request({ ...options, url: this.baseURL + url, success: (res) => { resolve(res.data) }, fail: (err) => { console.log("err:", err); } }) }) } get(options) { return this.request({ ...options, method: "get" }) } post(options) { return this.request({ ...options, method: "post" }) } } export const myReqInstance = new MyRequest("http://codercba.com:1888/api")
- Use encapsulated functions and classes
import { myRequest, myReqInstance } from "../../service/index"
Page({
data: {
allCities: {},
houselist: [],
currentPage: 1
},
async onLoad() {
// 1.网络请求基本使用
// wx.request({
// url: "http://codercba.com:1888/api/city/all",
// success: (res) => {
// const data = res.data.data
// this.setData({ allCities: data })
// },
// fail: (err) => {
// console.log("err:", err);
// }
// })
// wx.request({
// url: 'http://codercba.com:1888/api/home/houselist',
// data: {
// page: 1
// },
// success: (res) => {
// const data = res.data.data
// this.setData({ houselist: data })
// }
// })
// 2.使用封装的函数
// myRequest({
// url: "http://codercba.com:1888/api/city/all"
// }).then(res => {
// this.setData({ allCities: res.data })
// })
// myRequest({
// url: "http://codercba.com:1888/api/home/houselist",
// data: {
// page: 1
// }
// }).then(res => {
// this.setData({ houselist: res.data })
// })
// 3.await/async 书写方便,但性能不高,会阻塞后面的网络请求
// const cityRes = await myRequest({
// url: "http://codercba.com:1888/api/city/all"
// })
// this.setData({ allCities: cityRes.data })
// const houseRes = await myRequest({
// url: "http://codercba.com:1888/api/home/houselist",
// data: { page: 1 }
// })
// this.setData({ houselist: houseRes.data })
// 4.将请求封装到一个单独函数中(推荐) 异步函数执行不会阻塞后面的运行
this.getCityData()
this.getHouselistData()
// 5.使用类的实例发送请求
myReqInstance.get({
url: "/city/all"
}).then(res => {
console.log(res);
})
},
async getCityData() {
const cityRes = await myRequest({
url: "http://codercba.com:1888/api/city/all"
})
this.setData({ allCities: cityRes.data })
},
async getHouselistData() {
const houseRes = await myRequest({
url: "http://codercba.com:1888/api/home/houselist",
data: { page: this.data.currentPage }
})
const finalHouseList = [...this.data.houselist, ...houseRes.data]
this.setData({ houselist: finalHouseList })
// 思考: 为什么这里不需要setData?
// 修改currentPage数据,并不需要页面刷新
this.data.currentPage++
},
//上拉加载更多
onReachBottom() {
this.getHouselistData()
}
})
2. Display pop-up windows and page sharing
2.1 Display pop-up window
-
showToast displays a message prompt box
wx.showToast(Object object) | WeChat open document
-
showModal shows a modal dialog
wx.showModal(Object object) | WeChat open document
-
showLoading Show loading prompt box. Need to actively call wx.hideLoading to close the prompt box
wx.showLoading(Object object) | WeChat open document
-
showActionSheet shows the action menu
wx.showActionSheet(Object object) | WeChat open document
Notice
- wx.showLoading and wx.showToast can only display one at the same time
- wx.showToast should be paired with wx.hideToast
2.2 Page sharing
onShareAppMessage() {
return {
title: "旅途的内容",
path: "/pages/favor/favor",
imageUrl: "/assets/nhlt.jpg"
}
},
3. Device information and location information
3.1 Get device information wx.getSystemInfo(Object object) | WeChat Open Documentation
wx.getSystemInfo({
success (res) {
console.log(res.model)
console.log(res.pixelRatio)
console.log(res.windowWidth)
console.log(res.windowHeight)
console.log(res.language)
console.log(res.version)
console.log(res.platform)
}
})
3.2 Get Location Information wx.getLocation(Object object) | WeChat Open Documentation
Obtain user authorization global configuration | WeChat open document
4. Small program Storage storage
encrypt Boolean The default value is false optional
Whether to enable encrypted storage. Only the asynchronous setStorage interface supports enabling encrypted storage. After it is enabled, AES128 encryption will be used for data, and the interface callback time will increase. If encrypted storage is enabled, both setStorage and getStorage need to declare that the value of encrypt is true. In addition, since the encrypted data will be 1.4 times larger than the original data, when encrypt is turned on, the maximum data length allowed for a single key is 0.7MB, and the upper limit for all data storage is 7.1MB
5. Page jump and data transfer
5.1 Page Jump
5.1.1 navigator component navigator | WeChat open document
5.1.2 APIs of wx
Routing Jump API | Functional description |
Jump to the tabBar page and close all other non-tabBar pages | |
Close all pages, open to a page in the app | |
Close the current page and jump to a page in the app. But jumping to the tabbar page is not allowed. |
|
Keep the current page and jump to a page in the app. But can not jump to the tabbar page. Use wx.navigateBack to return to the original page. The page stack in the applet has a maximum of ten layers. | |
Close the current page and return to the previous page or multi-level pages. The current page stack can be obtained through getCurrentPages to determine how many layers need to be returned. |
5.2 Data transfer
Pass data to the upper level page
1. Get the instance of the previous page, and set data for the previous page through setData
- Write the data transfer process of returning to the previous page in onUnload(), and you can rewrite the return navigation function that comes with the applet to achieve parameter transfer
- Don't
App.onLaunch
call it when it is not generatedgetCurrentPages()
yetpage
.- Do not try to modify the page stack, it will cause routing and page state errors.
- getCurrentPages gets the current page stack. The first element in the array is the home page, and the last element is the current page
2. Function EventChannel that calls back events | WeChat Open Documentation
Pass data to the next level page
- Pass parameters between pages through the query field in the url, and obtain the parameters in the path to open the current page in the parameter options of the onLoad of the next level Page
- events 参数 EventChannel.on(string eventName, EventCallback fn)
Page({
data: {
name: "kobe",
age: 30,
message: "哈哈哈"
},
onNavTap() {
const name = this.data.name
const age = this.data.age
// 页面导航操作
wx.navigateTo({
// 跳转的过程, 传递一些参数过去
url: `/pages2/detail/detail?name=${name}&age=${age}`,
events: {
backEvent(data) {
console.log("back:", data);
},
coderwhy(data) {
console.log("why:", data);
}
}
})
}
})
Page({
data: {
name: "",
age: 0
},
// onLoad 的参数中获取打开当前页面路径中的参数。
onLoad(options) {
console.log(options);
const name = options.name
const age = options.age
this.setData({ name, age })
// const eventChannel = this.getOpenerEventChannel()
},
onBackTap() {
// 1.返回导航
wx.navigateBack()
// 2.方式一: 给上一级的页面传递数据
// 2.1. 获取到上一个页面的实例
// const pages = getCurrentPages()
// const prePage = pages[pages.length-2]
// // 2.2.通过setData给上一个页面设置数据
// prePage.setData({ message: "呵呵呵" })
// 3.方式二: 回调events的函数
// 3.1. 拿到eventChannel
const eventChannel = this.getOpenerEventChannel()
// 3.2. 通过eventChannel回调函数
eventChannel.emit("backEvent", { name: "back", age: 111 })
eventChannel.emit("coderwhy", { name: "why", age: 10 })
},
onUnload() {
// // 2.1. 获取到上一个页面的实例
// const pages = getCurrentPages()
// const prePage = pages[pages.length-2]
// // 2.2.通过setData给上一个页面设置数据
// prePage.setData({ message: "呵呵呵" })
}
})
6. Small program login process drill
Mini Program login process:
1. Obtain the code through wx.login()
2. Send this code to the backend, and the backend will return a token, which will be used as the unique identifier of the identity
3. Save the token in local storage through wx.setStorageSync()
4. When the user enters the page next time, the wx.getStorageSync() method will be used to determine whether the token has value and has not expired. If it has value and has not expired, it can request other data. If there is no value or the token is invalid, log in operate
Page({
// onLoad登录的流程
async onLoad() {
// 1.获取token, 判断token是否有值
const token = wx.getStorageSync('token') || ""
// 2.判断token是否过期
const res = await myLoginReqInstance.post({
url: "/auth",
header: {
token: token
}
})
// console.log(res);
// 2.如果token有值
if (token && res.message === "已登录") {
console.log("请求其他的数据");
} else {
this.handleLogin()
}
},
async handleLogin() {
// 1.获取code
const code = await getCode()
// 2.使用code换取token
const res = await myLoginReqInstance.post({
url: "/login",
data: { code }
})
// 3.保存token
wx.setStorageSync('token', res.token)
}
// handleLogin() {
// // 1.获取code
// wx.login({
// success: (res) => {
// const code = res.code
// // 2.将这个code发送自己的服务器(后端)
// wx.request({
// url: "http://123.207.32.32:3000/login",
// data: {
// code
// },
// method: "post",
// success: (res) => {
// const token = res.data.token
// wx.setStorageSync('token', token)
// }
// })
// }
// })
// }
})
Package getCode
// /service/login.js
export function getCode() {
return new Promise((resolve, reject) => {
wx.login({
success: (res) => {
resolve(res.code)
},
fail: reject
})
})
}