微信小程序101~110

发布于:2025-07-12 ⋅ 阅读:(14) ⋅ 点赞:(0)
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 返回 false
  return 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 instance


import 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.url
    options = { ...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
}

网站公告

今日签到

点亮在社区的每一天
去签到