1. 应用生命周期
1.1 应用生命周期钩子
// App.vue
<script>
export default {
// 应用初始化完成时触发(全局只触发一次)
onLaunch(options) {
console.log('App Launch', options)
// 获取启动参数
console.log('启动路径:', options.path)
console.log('启动参数:', options.query)
console.log('启动场景值:', options.scene)
// 初始化全局数据
this.initGlobalData()
// 检查更新
this.checkForUpdate()
// 初始化第三方SDK
this.initSDK()
},
// 应用显示时触发
onShow(options) {
console.log('App Show', options)
// 应用从后台进入前台
this.handleAppShow()
// 检查网络状态
this.checkNetworkStatus()
// 更新用户信息
this.updateUserInfo()
},
// 应用隐藏时触发
onHide() {
console.log('App Hide')
// 应用进入后台
this.handleAppHide()
// 保存应用状态
this.saveAppState()
// 暂停音频播放等
this.pauseMedia()
},
// 应用发生错误时触发
onError(error) {
console.error('App Error:', error)
// 错误上报
this.reportError(error)
// 错误处理
this.handleError(error)
},
// 页面不存在时触发
onPageNotFound(res) {
console.log('Page Not Found:', res)
// 重定向到首页或404页面
uni.redirectTo({
url: '/pages/index/index'
})
},
// 未处理的Promise拒绝时触发
onUnhandledRejection(res) {
console.error('Unhandled Rejection:', res)
// 处理未捕获的Promise错误
this.handleUnhandledRejection(res)
},
// 主题改变时触发(仅微信小程序)
onThemeChange(res) {
console.log('Theme Change:', res.theme)
// 处理主题变化
this.handleThemeChange(res.theme)
},
methods: {
initGlobalData() {
// 初始化全局数据
this.globalData = {
userInfo: null,
token: uni.getStorageSync('token') || '',
theme: 'light',
version: '1.0.0'
}
},
checkForUpdate() {
// 检查应用更新(仅小程序)
if (uni.canIUse('getUpdateManager')) {
const updateManager = uni.getUpdateManager()
updateManager.onCheckForUpdate((res) => {
console.log('检查更新结果:', res.hasUpdate)
})
updateManager.onUpdateReady(() => {
uni.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success: (res) => {
if (res.confirm) {
updateManager.applyUpdate()
}
}
})
})
updateManager.onUpdateFailed(() => {
console.error('更新失败')
})
}
},
initSDK() {
// 初始化第三方SDK
console.log('初始化第三方SDK')
},
handleAppShow() {
// 应用显示处理
console.log('应用显示处理')
},
handleAppHide() {
// 应用隐藏处理
console.log('应用隐藏处理')
},
checkNetworkStatus() {
uni.getNetworkType({
success: (res) => {
console.log('网络类型:', res.networkType)
this.globalData.networkType = res.networkType
}
})
},
updateUserInfo() {
// 更新用户信息
const token = uni.getStorageSync('token')
if (token) {
// 获取最新用户信息
this.getUserInfo()
}
},
saveAppState() {
// 保存应用状态
try {
uni.setStorageSync('appState', {
timestamp: Date.now(),
data: this.globalData
})
} catch (error) {
console.error('保存应用状态失败:', error)
}
},
pauseMedia() {
// 暂停媒体播放
console.log('暂停媒体播放')
},
reportError(error) {
// 错误上报
console.log('错误上报:', error)
},
handleError(error) {
// 错误处理
uni.showToast({
title: '应用发生错误',
icon: 'none'
})
},
handleUnhandledRejection(res) {
// 处理未捕获的Promise错误
console.error('未处理的Promise拒绝:', res.reason)
},
handleThemeChange(theme) {
// 处理主题变化
this.globalData.theme = theme
// 通知所有页面主题已变化
uni.$emit('themeChange', theme)
},
getUserInfo() {
// 获取用户信息的方法
return new Promise((resolve, reject) => {
// 模拟API调用
setTimeout(() => {
resolve({
id: 1,
name: 'John Doe',
avatar: '/static/avatar.png'
})
}, 1000)
})
}
},
globalData: {
userInfo: null,
token: '',
theme: 'light',
version: '1.0.0',
networkType: 'unknown'
}
}
</script>
2. 页面生命周期
2.1 页面生命周期钩子
<template>
<view class="container">
<text>页面生命周期演示</text>
<text>页面加载次数:{{ loadCount }}</text>
<text>页面显示次数:{{ showCount }}</text>
<button @click="navigateToOther">跳转到其他页面</button>
</view>
</template>
<script>
export default {
data() {
return {
loadCount: 0,
showCount: 0,
startTime: 0,
pageData: null
}
},
// 页面加载时触发,只会调用一次
onLoad(options) {
console.log('页面加载 onLoad', options)
this.loadCount++
this.startTime = Date.now()
// 获取页面参数
console.log('页面参数:', options)
// 初始化页面数据
this.initPageData(options)
// 设置页面标题
uni.setNavigationBarTitle({
title: '生命周期演示'
})
// 显示加载中
uni.showLoading({
title: '加载中...'
})
// 模拟数据加载
this.loadData().then(() => {
uni.hideLoading()
})
},
// 页面显示时触发,每次显示都会调用
onShow() {
console.log('页面显示 onShow')
this.showCount++
// 页面显示时的处理
this.handlePageShow()
// 刷新数据
this.refreshData()
// 统计页面访问
this.trackPageView()
},
// 页面初次渲染完成时触发,只会调用一次
onReady() {
console.log('页面初次渲染完成 onReady')
// 页面渲染完成后的处理
this.handlePageReady()
// 获取节点信息
this.getNodeInfo()
// 初始化动画
this.initAnimation()
},
// 页面隐藏时触发
onHide() {
console.log('页面隐藏 onHide')
// 页面隐藏时的处理
this.handlePageHide()
// 保存页面状态
this.savePageState()
// 暂停定时器
this.pauseTimers()
},
// 页面卸载时触发
onUnload() {
console.log('页面卸载 onUnload')
const endTime = Date.now()
const duration = endTime - this.startTime
console.log(`页面停留时间: ${duration}ms`)
// 页面卸载时的清理工作
this.cleanup()
// 统计页面停留时间
this.trackPageDuration(duration)
// 清除定时器
this.clearTimers()
// 移除事件监听
this.removeEventListeners()
},
// 监听用户下拉刷新事件
onPullDownRefresh() {
console.log('下拉刷新 onPullDownRefresh')
// 执行刷新操作
this.refreshData().then(() => {
// 停止下拉刷新
uni.stopPullDownRefresh()
})
},
// 监听用户上拉触底事件
onReachBottom() {
console.log('上拉触底 onReachBottom')
// 加载更多数据
this.loadMoreData()
},
// 监听用户点击右上角分享
onShareAppMessage() {
console.log('分享 onShareAppMessage')
return {
title: '生命周期演示页面',
path: '/pages/lifecycle/lifecycle',
imageUrl: '/static/share.png'
}
},
// 监听用户点击右上角分享到朋友圈(仅微信小程序)
onShareTimeline() {
console.log('分享到朋友圈 onShareTimeline')
return {
title: '生命周期演示',
imageUrl: '/static/timeline.png'
}
},
// 监听页面滚动
onPageScroll(e) {
// console.log('页面滚动', e.scrollTop)
// 处理滚动事件(注意性能)
this.handlePageScroll(e.scrollTop)
},
// 监听窗口尺寸变化
onResize(res) {
console.log('窗口尺寸变化', res)
// 处理窗口尺寸变化
this.handleResize(res)
},
// 监听tab点击(仅TabBar页面)
onTabItemTap(item) {
console.log('Tab点击', item)
// 处理Tab点击
this.handleTabTap(item)
},
methods: {
initPageData(options) {
// 初始化页面数据
this.pageData = {
id: options.id || null,
type: options.type || 'default',
timestamp: Date.now()
}
},
async loadData() {
// 模拟数据加载
return new Promise((resolve) => {
setTimeout(() => {
console.log('数据加载完成')
resolve()
}, 2000)
})
},
handlePageShow() {
// 页面显示处理
console.log('处理页面显示')
},
refreshData() {
// 刷新数据
console.log('刷新数据')
return Promise.resolve()
},
trackPageView() {
// 统计页面访问
console.log('统计页面访问')
},
handlePageReady() {
// 页面准备完成处理
console.log('页面准备完成')
},
getNodeInfo() {
// 获取节点信息
const query = uni.createSelectorQuery().in(this)
query.select('.container').boundingClientRect((data) => {
console.log('容器节点信息:', data)
}).exec()
},
initAnimation() {
// 初始化动画
console.log('初始化动画')
},
handlePageHide() {
// 页面隐藏处理
console.log('处理页面隐藏')
},
savePageState() {
// 保存页面状态
try {
uni.setStorageSync('pageState', {
data: this.pageData,
timestamp: Date.now()
})
} catch (error) {
console.error('保存页面状态失败:', error)
}
},
pauseTimers() {
// 暂停定时器
console.log('暂停定时器')
},
cleanup() {
// 清理工作
console.log('执行清理工作')
},
trackPageDuration(duration) {
// 统计页面停留时间
console.log('页面停留时间统计:', duration)
},
clearTimers() {
// 清除定时器
console.log('清除定时器')
},
removeEventListeners() {
// 移除事件监听
console.log('移除事件监听')
},
loadMoreData() {
// 加载更多数据
console.log('加载更多数据')
},
handlePageScroll(scrollTop) {
// 处理页面滚动(节流处理)
if (!this.scrollTimer) {
this.scrollTimer = setTimeout(() => {
// 实际的滚动处理逻辑
console.log('处理滚动:', scrollTop)
this.scrollTimer = null
}, 100)
}
},
handleResize(res) {
// 处理窗口尺寸变化
console.log('处理窗口尺寸变化:', res)
},
handleTabTap(item) {
// 处理Tab点击
console.log('处理Tab点击:', item)
},
navigateToOther() {
uni.navigateTo({
url: '/pages/other/other?from=lifecycle'
})
}
}
}
</script>
3. 组件生命周期
3.1 组件生命周期钩子
<!-- components/lifecycle-demo/lifecycle-demo.vue -->
<template>
<view class="lifecycle-component">
<text>组件生命周期演示</text>
<text>组件ID: {{ componentId }}</text>
<text>更新次数: {{ updateCount }}</text>
<button @click="updateData">更新数据</button>
<button @click="$emit('destroy')">销毁组件</button>
</view>
</template>
<script>
export default {
name: 'LifecycleDemo',
props: {
componentId: {
type: String,
default: 'default'
},
initialData: {
type: Object,
default: () => ({})
}
},
data() {
return {
updateCount: 0,
internalData: null,
timer: null
}
},
// 组件实例被创建之后立即调用
beforeCreate() {
console.log('组件 beforeCreate')
// 此时data和methods还未初始化
},
// 组件实例创建完成,data和methods已初始化
created() {
console.log('组件 created')
// 初始化组件数据
this.initComponentData()
// 设置定时器
this.startTimer()
// 监听全局事件
this.addGlobalListeners()
},
// 组件挂载之前调用
beforeMount() {
console.log('组件 beforeMount')
// 此时模板编译完成,但还未挂载到DOM
},
// 组件挂载完成后调用
mounted() {
console.log('组件 mounted')
// 组件挂载完成后的处理
this.handleMounted()
// 获取组件节点信息
this.getComponentInfo()
// 初始化第三方插件
this.initPlugins()
},
// 组件更新之前调用
beforeUpdate() {
console.log('组件 beforeUpdate')
// 数据更新前的处理
},
// 组件更新完成后调用
updated() {
console.log('组件 updated')
this.updateCount++
// 组件更新后的处理
this.handleUpdated()
},
// 组件销毁之前调用
beforeDestroy() {
console.log('组件 beforeDestroy')
// 清理工作
this.cleanup()
// 清除定时器
this.clearTimer()
// 移除全局事件监听
this.removeGlobalListeners()
},
// 组件销毁完成后调用
destroyed() {
console.log('组件 destroyed')
// 最终清理工作
this.finalCleanup()
},
methods: {
initComponentData() {
// 初始化组件数据
this.internalData = {
...this.initialData,
createdAt: Date.now()
}
console.log('组件数据初始化完成')
},
startTimer() {
// 启动定时器
this.timer = setInterval(() => {
console.log('组件定时器执行')
}, 5000)
},
addGlobalListeners() {
// 添加全局事件监听
uni.$on('globalEvent', this.handleGlobalEvent)
},
handleMounted() {
// 组件挂载完成处理
console.log('组件挂载完成处理')
},
getComponentInfo() {
// 获取组件信息
const query = uni.createSelectorQuery().in(this)
query.select('.lifecycle-component').boundingClientRect((data) => {
console.log('组件节点信息:', data)
}).exec()
},
initPlugins() {
// 初始化第三方插件
console.log('初始化第三方插件')
},
handleUpdated() {
// 组件更新后处理
console.log('组件更新后处理')
},
updateData() {
// 更新数据
this.internalData = {
...this.internalData,
updatedAt: Date.now()
}
},
cleanup() {
// 清理工作
console.log('组件清理工作')
},
clearTimer() {
// 清除定时器
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
},
removeGlobalListeners() {
// 移除全局事件监听
uni.$off('globalEvent', this.handleGlobalEvent)
},
finalCleanup() {
// 最终清理工作
console.log('组件最终清理工作')
},
handleGlobalEvent(data) {
// 处理全局事件
console.log('组件接收到全局事件:', data)
}
}
}
</script>
<style>
.lifecycle-component {
padding: 20rpx;
border: 2rpx solid #007aff;
border-radius: 10rpx;
margin: 20rpx;
}
</style>
4. UniApp API调用
4.1 网络请求API
// utils/request.js - 网络请求封装
class RequestManager {
constructor() {
this.baseURL = 'https://api.example.com'
this.timeout = 10000
this.interceptors = {
request: [],
response: []
}
}
// 添加请求拦截器
addRequestInterceptor(interceptor) {
this.interceptors.request.push(interceptor)
}
// 添加响应拦截器
addResponseInterceptor(interceptor) {
this.interceptors.response.push(interceptor)
}
// 发送请求
async request(options) {
// 合并默认配置
const config = {
url: this.baseURL + options.url,
method: options.method || 'GET',
data: options.data || {},
header: {
'Content-Type': 'application/json',
...options.header
},
timeout: options.timeout || this.timeout
}
// 执行请求拦截器
for (const interceptor of this.interceptors.request) {
config = await interceptor(config)
}
try {
// 发送请求
const response = await this.sendRequest(config)
// 执行响应拦截器
let result = response
for (const interceptor of this.interceptors.response) {
result = await interceptor(result)
}
return result
} catch (error) {
// 错误处理
throw this.handleError(error)
}
}
// 发送实际请求
sendRequest(config) {
return new Promise((resolve, reject) => {
uni.request({
...config,
success: (res) => {
resolve({
data: res.data,
statusCode: res.statusCode,
header: res.header,
config
})
},
fail: (error) => {
reject({
error,
config
})
}
})
})
}
// 错误处理
handleError(error) {
console.error('请求错误:', error)
if (error.error) {
// 网络错误
return {
code: 'NETWORK_ERROR',
message: '网络连接失败',
original: error
}
}
return error
}
// GET请求
get(url, params = {}, options = {}) {
return this.request({
url,
method: 'GET',
data: params,
...options
})
}
// POST请求
post(url, data = {}, options = {}) {
return this.request({
url,
method: 'POST',
data,
...options
})
}
// PUT请求
put(url, data = {}, options = {}) {
return this.request({
url,
method: 'PUT',
data,
...options
})
}
// DELETE请求
delete(url, options = {}) {
return this.request({
url,
method: 'DELETE',
...options
})
}
// 上传文件
upload(url, filePath, options = {}) {
return new Promise((resolve, reject) => {
uni.uploadFile({
url: this.baseURL + url,
filePath,
name: options.name || 'file',
formData: options.formData || {},
header: options.header || {},
success: (res) => {
resolve({
data: JSON.parse(res.data),
statusCode: res.statusCode
})
},
fail: reject
})
})
}
// 下载文件
download(url, options = {}) {
return new Promise((resolve, reject) => {
uni.downloadFile({
url: this.baseURL + url,
header: options.header || {},
success: (res) => {
if (res.statusCode === 200) {
resolve({
tempFilePath: res.tempFilePath,
statusCode: res.statusCode
})
} else {
reject(new Error('下载失败'))
}
},
fail: reject
})
})
}
}
// 创建请求实例
const request = new RequestManager()
// 添加请求拦截器
request.addRequestInterceptor(async (config) => {
// 添加token
const token = uni.getStorageSync('token')
if (token) {
config.header.Authorization = `Bearer ${token}`
}
// 显示加载中
uni.showLoading({
title: '请求中...',
mask: true
})
console.log('发送请求:', config)
return config
})
// 添加响应拦截器
request.addResponseInterceptor(async (response) => {
// 隐藏加载中
uni.hideLoading()
console.log('收到响应:', response)
// 统一处理响应
if (response.statusCode === 200) {
const { code, data, message } = response.data
if (code === 0) {
return data
} else if (code === 401) {
// token过期,跳转到登录页
uni.removeStorageSync('token')
uni.navigateTo({
url: '/pages/login/login'
})
throw new Error('登录已过期')
} else {
throw new Error(message || '请求失败')
}
} else {
throw new Error(`HTTP ${response.statusCode}`)
}
})
export default request
4.2 存储API
// utils/storage.js - 存储管理
class StorageManager {
constructor() {
this.prefix = 'app_'
}
// 生成完整的key
getFullKey(key) {
return this.prefix + key
}
// 同步设置存储
setSync(key, value) {
try {
const fullKey = this.getFullKey(key)
const data = {
value,
timestamp: Date.now(),
type: typeof value
}
uni.setStorageSync(fullKey, data)
return true
} catch (error) {
console.error('设置存储失败:', error)
return false
}
}
// 异步设置存储
set(key, value) {
return new Promise((resolve, reject) => {
try {
const fullKey = this.getFullKey(key)
const data = {
value,
timestamp: Date.now(),
type: typeof value
}
uni.setStorage({
key: fullKey,
data,
success: () => resolve(true),
fail: reject
})
} catch (error) {
reject(error)
}
})
}
// 同步获取存储
getSync(key, defaultValue = null) {
try {
const fullKey = this.getFullKey(key)
const data = uni.getStorageSync(fullKey)
if (data && data.value !== undefined) {
return data.value
}
return defaultValue
} catch (error) {
console.error('获取存储失败:', error)
return defaultValue
}
}
// 异步获取存储
get(key, defaultValue = null) {
return new Promise((resolve) => {
try {
const fullKey = this.getFullKey(key)
uni.getStorage({
key: fullKey,
success: (res) => {
if (res.data && res.data.value !== undefined) {
resolve(res.data.value)
} else {
resolve(defaultValue)
}
},
fail: () => resolve(defaultValue)
})
} catch (error) {
resolve(defaultValue)
}
})
}
// 同步删除存储
removeSync(key) {
try {
const fullKey = this.getFullKey(key)
uni.removeStorageSync(fullKey)
return true
} catch (error) {
console.error('删除存储失败:', error)
return false
}
}
// 异步删除存储
remove(key) {
return new Promise((resolve, reject) => {
try {
const fullKey = this.getFullKey(key)
uni.removeStorage({
key: fullKey,
success: () => resolve(true),
fail: reject
})
} catch (error) {
reject(error)
}
})
}
// 清空所有存储
clear() {
return new Promise((resolve, reject) => {
uni.clearStorage({
success: () => resolve(true),
fail: reject
})
})
}
// 获取存储信息
getInfo() {
return new Promise((resolve, reject) => {
uni.getStorageInfo({
success: (res) => {
resolve({
keys: res.keys.filter(key => key.startsWith(this.prefix)),
currentSize: res.currentSize,
limitSize: res.limitSize
})
},
fail: reject
})
})
}
// 设置带过期时间的存储
setWithExpiry(key, value, expiryTime) {
const data = {
value,
timestamp: Date.now(),
expiry: Date.now() + expiryTime
}
return this.setSync(key, data)
}
// 获取带过期时间的存储
getWithExpiry(key, defaultValue = null) {
const data = this.getSync(key)
if (data && data.expiry) {
if (Date.now() > data.expiry) {
// 已过期,删除数据
this.removeSync(key)
return defaultValue
}
return data.value
}
return data || defaultValue
}
}
// 创建存储实例
const storage = new StorageManager()
export default storage
4.3 设备API
// utils/device.js - 设备信息管理
class DeviceManager {
constructor() {
this.systemInfo = null
this.networkInfo = null
}
// 获取系统信息
async getSystemInfo() {
if (this.systemInfo) {
return this.systemInfo
}
return new Promise((resolve, reject) => {
uni.getSystemInfo({
success: (res) => {
this.systemInfo = res
resolve(res)
},
fail: reject
})
})
}
// 获取网络信息
async getNetworkInfo() {
return new Promise((resolve, reject) => {
uni.getNetworkType({
success: (res) => {
this.networkInfo = res
resolve(res)
},
fail: reject
})
})
}
// 监听网络状态变化
onNetworkStatusChange(callback) {
uni.onNetworkStatusChange(callback)
}
// 获取位置信息
async getLocation(options = {}) {
return new Promise((resolve, reject) => {
uni.getLocation({
type: options.type || 'wgs84',
altitude: options.altitude || false,
success: resolve,
fail: reject
})
})
}
// 选择位置
async chooseLocation() {
return new Promise((resolve, reject) => {
uni.chooseLocation({
success: resolve,
fail: reject
})
})
}
// 打开地图
openLocation(latitude, longitude, options = {}) {
return new Promise((resolve, reject) => {
uni.openLocation({
latitude,
longitude,
name: options.name || '',
address: options.address || '',
scale: options.scale || 18,
success: resolve,
fail: reject
})
})
}
// 获取设备信息
async getDeviceInfo() {
const systemInfo = await this.getSystemInfo()
const networkInfo = await this.getNetworkInfo()
return {
// 系统信息
platform: systemInfo.platform,
system: systemInfo.system,
version: systemInfo.version,
model: systemInfo.model,
brand: systemInfo.brand,
// 屏幕信息
screenWidth: systemInfo.screenWidth,
screenHeight: systemInfo.screenHeight,
windowWidth: systemInfo.windowWidth,
windowHeight: systemInfo.windowHeight,
pixelRatio: systemInfo.pixelRatio,
// 网络信息
networkType: networkInfo.networkType,
// 其他信息
language: systemInfo.language,
fontSizeSetting: systemInfo.fontSizeSetting,
SDKVersion: systemInfo.SDKVersion
}
}
// 振动
vibrate(type = 'short') {
if (type === 'long') {
uni.vibrateLong()
} else {
uni.vibrateShort()
}
}
// 设置屏幕亮度
setScreenBrightness(value) {
return new Promise((resolve, reject) => {
uni.setScreenBrightness({
value,
success: resolve,
fail: reject
})
})
}
// 获取屏幕亮度
getScreenBrightness() {
return new Promise((resolve, reject) => {
uni.getScreenBrightness({
success: resolve,
fail: reject
})
})
}
// 保持屏幕常亮
setKeepScreenOn(keepScreenOn = true) {
return new Promise((resolve, reject) => {
uni.setKeepScreenOn({
keepScreenOn,
success: resolve,
fail: reject
})
})
}
// 监听加速度数据
startAccelerometer(interval = 'normal') {
return new Promise((resolve, reject) => {
uni.startAccelerometer({
interval,
success: resolve,
fail: reject
})
})
}
// 停止监听加速度数据
stopAccelerometer() {
return new Promise((resolve, reject) => {
uni.stopAccelerometer({
success: resolve,
fail: reject
})
})
}
// 监听加速度数据变化
onAccelerometerChange(callback) {
uni.onAccelerometerChange(callback)
}
// 监听罗盘数据
startCompass() {
return new Promise((resolve, reject) => {
uni.startCompass({
success: resolve,
fail: reject
})
})
}
// 停止监听罗盘数据
stopCompass() {
return new Promise((resolve, reject) => {
uni.stopCompass({
success: resolve,
fail: reject
})
})
}
// 监听罗盘数据变化
onCompassChange(callback) {
uni.onCompassChange(callback)
}
// 拨打电话
makePhoneCall(phoneNumber) {
return new Promise((resolve, reject) => {
uni.makePhoneCall({
phoneNumber,
success: resolve,
fail: reject
})
})
}
// 扫码
scanCode(options = {}) {
return new Promise((resolve, reject) => {
uni.scanCode({
onlyFromCamera: options.onlyFromCamera || false,
scanType: options.scanType || ['barCode', 'qrCode'],
success: resolve,
fail: reject
})
})
}
// 获取剪贴板内容
getClipboardData() {
return new Promise((resolve, reject) => {
uni.getClipboardData({
success: resolve,
fail: reject
})
})
}
// 设置剪贴板内容
setClipboardData(data) {
return new Promise((resolve, reject) => {
uni.setClipboardData({
data,
success: resolve,
fail: reject
})
})
}
}
// 创建设备管理实例
const device = new DeviceManager()
export default device
4.4 API使用示例
<template>
<view class="api-demo">
<view class="section">
<text class="title">网络请求</text>
<button @click="testRequest">测试请求</button>
<button @click="uploadFile">上传文件</button>
</view>
<view class="section">
<text class="title">存储管理</text>
<button @click="testStorage">测试存储</button>
<button @click="getStorageInfo">存储信息</button>
</view>
<view class="section">
<text class="title">设备信息</text>
<button @click="getDeviceInfo">获取设备信息</button>
<button @click="getLocation">获取位置</button>
<button @click="scanCode">扫码</button>
</view>
<view class="result">
<text>{{ result }}</text>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
import storage from '@/utils/storage.js'
import device from '@/utils/device.js'
export default {
data() {
return {
result: '点击按钮测试API'
}
},
methods: {
async testRequest() {
try {
this.result = '请求中...'
const data = await request.get('/api/test')
this.result = JSON.stringify(data, null, 2)
} catch (error) {
this.result = '请求失败: ' + error.message
}
},
async uploadFile() {
try {
const res = await uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera']
})
if (res.tempFilePaths.length > 0) {
this.result = '上传中...'
const uploadRes = await request.upload('/api/upload', res.tempFilePaths[0])
this.result = '上传成功: ' + JSON.stringify(uploadRes, null, 2)
}
} catch (error) {
this.result = '上传失败: ' + error.message
}
},
async testStorage() {
try {
// 设置存储
await storage.set('testKey', { name: 'test', value: 123 })
// 获取存储
const data = await storage.get('testKey')
this.result = '存储测试成功: ' + JSON.stringify(data, null, 2)
} catch (error) {
this.result = '存储测试失败: ' + error.message
}
},
async getStorageInfo() {
try {
const info = await storage.getInfo()
this.result = '存储信息: ' + JSON.stringify(info, null, 2)
} catch (error) {
this.result = '获取存储信息失败: ' + error.message
}
},
async getDeviceInfo() {
try {
const info = await device.getDeviceInfo()
this.result = '设备信息: ' + JSON.stringify(info, null, 2)
} catch (error) {
this.result = '获取设备信息失败: ' + error.message
}
},
async getLocation() {
try {
this.result = '获取位置中...'
const location = await device.getLocation()
this.result = '位置信息: ' + JSON.stringify(location, null, 2)
} catch (error) {
this.result = '获取位置失败: ' + error.message
}
},
async scanCode() {
try {
const res = await device.scanCode()
this.result = '扫码结果: ' + JSON.stringify(res, null, 2)
} catch (error) {
this.result = '扫码失败: ' + error.message
}
}
}
}
</script>
<style>
.api-demo {
padding: 40rpx;
}
.section {
margin-bottom: 40rpx;
padding: 20rpx;
border: 2rpx solid #e5e5e5;
border-radius: 10rpx;
}
.title {
font-size: 32rpx;
font-weight: bold;
margin-bottom: 20rpx;
display: block;
}
button {
margin: 10rpx;
font-size: 28rpx;
}
.result {
padding: 20rpx;
background-color: #f5f5f5;
border-radius: 10rpx;
margin-top: 20rpx;
font-size: 24rpx;
word-break: break-all;
}
</style>
5. 总结
本章详细介绍了UniApp中的生命周期和API调用:
- 应用生命周期:掌握了应用级别的生命周期钩子和处理方法
- 页面生命周期:学习了页面级别的生命周期管理和最佳实践
- 组件生命周期:了解了组件的创建、更新和销毁过程
- API调用:实现了网络请求、存储管理、设备信息等API的封装和使用
这些知识是构建复杂UniApp应用的核心,下一章我们将学习状态管理与数据存储。