当前位置: 首页 > news >正文

微信小程序101~110

1.封装消息提示模块

为了减少代码冗余。

// 在使用toast方法时,可以传入参数,也可以不传入参数
// 如果要传入参数,要传入对象作为参数
// const toast = (options = {}) => {}// 如果用户传入了对象作为参数
// 在形参位置通过解构的方法获取用户传入的参数,同时设置默认值
const toast = ({ title = '数据加载中...', icon = 'none', duration = 2000, mark = true } = {}) => {wx.showToast({title,icon,duration,mask})
}
// 如果有很多.js文件,都需要调用toast方法
// 可以将toast方法挂载到wx全局对象身上
// 如果这种方法生效,要让当前文件执行一次
wx.toast = toast// 如果.js文件,需要使用toast方法
// 需要先导入 toast,调用才行
export { toast }第一种方法在.js中调用
toast()
第二种方法在toast中调用
wx.toast()
2.模块对话框封装
// 在使用modal方法时,可以传入参数,也可以不传入参数
// 如果要传入参数,要传入对象作为参数,对象中的属性要和wx.showModal 的参数保持一致
const modal = (options = {}) => {// 在方法内需要通过Promise返回用户的操作// 如果用户点击了确定,需要通过resolve 返回 true// 如果用户点击了取消,需要通过resolve 返回 falsereturn new Promise((resolve) => {// 默认的参数const defaultOpt = {title: '提示',content: '您确定执行该操作吗?',confirmColor: '#f3514f'}// 通过Object.assign 方法将参数进行合并// 将传入的参数覆盖默认的参数// 为了不影响默认的参数,需要将合并后的参数赋值给一个空对象const opts = Object.assign({}, defaultOpt, options)wx.showModal({// 将合并后的参数通过展开运算符赋值给wx.showModal 对象...opts,// 回调函数,不管用户点击取消或确定都会执行complete({ confirm, cancel }) {confirm && resolve(true)cancel && resolve(false)}})})
}// 如果有很多.js文件,都需要调用modal 方法
// 可以将modal 方法挂载到wx全局对象身上
// 如果这种方法生效,要让当前文件执行一次
wx.modal = modal// 如果.js文件,需要使用modal 方法
// 需要先导入 modal ,调用才行
export { toast, modal }

在这里插入图片描述

3. 本地存储API

将数据存储到本地,方便多个页面的读取使用。如:用户的登录状态,用户的个人信息存储到本地。
有同步、异步两类api来实现本地存储操作。

1.存储
const setStorage = (key, value) => {try {wx.setStorageSync('key', value)} catch (error) {console.log(`存储指定 ${key} 数据发生了异常`, error)}
}
2.读取
const getStorage = (key) => {try {const value = wx.setStorageSync(key)if (value) {return value}} catch (error) {console.log(`读取指定 ${key} 数据发生了异常`, error)}
}
3.移除
const removeStorage = (key) => {try {wx.removeStorageSync(key)} catch (error) {console.log(`移除指定 ${key} 数据发生了异常`, error)}
}
4.清空
const clearStorage = (key) => {try {wx.clearStorageSync()} catch (error) {console.log(`清除、清空数据发生了异常`, error)}
}
5.异步存储
export const asyncSetStorage = (key, data) => {return new Promise((resolve) => {wx.setStorage({key,data,complete(res) {resolve(res)}})})
}
6.异步获取
export const asyncGetStorage = (key) => {return new Promise((resolve) => {wx.getStorage({key,complete(res) {resolve(res)}})})
}
7.异步移除
export const asyncRmoveStorage = (key) => {return new Promise((resolve) => {wx.removeStorage({key,complete(res) {resolve(res)}})})
}
8. 异步清空
export const asyncClearStorage = () => {return new Promise((resolve) => {wx.clearStorage({complete(res) {resolve(res)}})})
}asyncClearStorage().then((res) => {console.log(res)
}) 
4.网络请求模块的封装-request

创建wxRequest类,通过类的方式进行封装,会让代码更具有复用性,也可以方便添加新的属性和方法。
需要使用promise封装wx.request处理异步请求。

class wxRequest {constructor() {}request(options) {return new Promise((resolve, reject) => {wx.request({...options,success: (res) => {resolve(res)},fail: (err) => {reject(err)}})})}
}// 实例化
const inxtance = new WxRequest()export default instanceimport instance from '../../utils/request'
Page({handler() {// 第一种调用方法instance.request({url: '',methods: 'GET'}).then((res) => {console.log(res)})// 第二种const res = await instance.request({url: '',methods: 'GET'})console.log(res)}})
5.请求封装-设置请求参数
  1. 默认参数:在WxRequest类中添加defaults实例属性来设置默认值
  2. 实例化时参数:在对WxRequest类进行实例化时传入相关的参数,需要在constructor构造函数形参进行接收
  3. 调用实例方法时传入请求参数
class wxRequest {defaults = {baseURL: '', // 请求基准地址url: '', // 接口的请求路径data: null, // 请求参数methods: 'GET', // 默认的请求方法// 请求头header: {'Content-type': 'application/json' // 设置数据的交互格式},timeout: 60000 // 默认的超时时长,默认为一分钟}// 实例化时传入的参数会被constructor形参进行接收constructor(params = {}) {this.default = Object.assign({}, this.defaults, params)}request(options) {options.url = this.defaults.baseURL + options.urloptions = { ...this.defaults, ...options }return new Promise((resolve, reject) => {wx.request({...options,success: (res) => {resolve(res)},fail: (err) => {reject(err)}})})}
}// 实例化
const inxtance = new WxRequest({baseURL: '',timeout: 15000
})export default instance
6.封装请求快捷方法

// get方法get(url, data = {}, config = {}) {return this.request(Object.assign({ url, data, methods: 'GET' }, config))}// delete方法delete(url, data = {}, config = {}) {return this.request(Object.assign({ url, data, methods: 'DELETE' }, config))}
//post方法post(url, data = {}, config = {}) {return this.request(Object.assign({ url, data, methods: 'POST' }, config))}
// put方法put(url, data = {}, config = {}) {return this.request(Object.assign({ url, data, methods: 'PUT' }, config))}// 接收带参数数据
const res = await instance.get('/index/findBanner', { test: 111 }, { timeout: 20000 })
7.wx.request注意事项
  1. 只要成功接收到服务器返回的结果,无论statusCode、状态码是多少都会执行success
  2. 一般在网络出现异常时(网络超时),就会执行fail
8.定义请求-响应拦截器

为了方便统一请求参数以及服务器响应结果,为WxRequest添加拦截器功能。

  1. 请求拦截器:是请求之前调用的函数,用来对请求函数进行新增和删改
  2. 响应拦截器:响应之后调用的数据,用来对响应数据做点什么

注意:不管响应成功还是失败,都会执行响应拦截器

  interceptors = {// 请求拦截器request: (config) => config,//响应拦截器response: (response) => response}//配置请求拦截器
instance.interceptors.request = (config) => {return config
}
//配置响应拦截器
instance.interceptors.response = (response) => {return response
}
http://www.dtcms.com/a/271837.html

相关文章:

  • 以太网基础⑤UDP 协议原理与 FPGA 实现
  • 2025年7月9日学习笔记——模式识别与机器学习——fisher线性回归、感知器、最小二乘法、最小误差判别算法、罗杰斯特回归算法——线性分类器
  • 【TCP/IP】1. 概述
  • AI赋能生活:深度解析与技术洞察
  • LiteHub之文件下载与视频播放
  • 微信小程序控制空调之EMQX服务器安装与配置
  • 重新配置电脑中的环境变量
  • SpringBoot ThreadLocal 全局动态变量设置
  • 机器学习11——支持向量机上
  • 初学者对编译和链接的学习笔记(含预编译详解)
  • 广告匹配策略的智能化之路:人工智能大模型的方法和步骤
  • 多模态大语言模型arxiv论文略读(156)
  • vivo Pulsar 万亿级消息处理实践(3)-KoP指标异常修复
  • 快速上手MongoDB与.NET/C#整合
  • 【AI大模型】LLM模型架构深度解析:BERT vs. GPT vs. T5
  • searxng 对接openweb-UI实现大模型通过国内搜索引擎在线搜索
  • 搜索引擎vs向量数据库:LangChain混合检索架构实战解析
  • 计算机视觉 之 数字图像处理基础
  • 基于 SpringBoot + Vue 的 IT 技术交流和分享平台的设计与实现
  • TCP-与-UDP-协议详解:原理、区别与应用场景全解析
  • 北斗舞动在线监测装置:电力安全的“智慧守护者”
  • SpringMVC @ExceptionHandler 典型用法
  • 了解去中心化金融在现代经济中的作用——安全交易新时代
  • 编写bat文件自动打开chrome浏览器,并通过selenium抓取浏览器操作chrome
  • 双指针-18.四数之和-力扣(LeetCode)
  • linux系统---ISCSI存储服务
  • Language Models are Few-Shot Learners: 开箱即用的GPT-3(二)
  • 节点小宝:手机图片备份至电脑功能实测体验
  • 同一类型,每条数据,执行不同逻辑
  • 偏振相机,偏振图像是怎么样的