uni-app 入门学习教程,从入门到精通, uni-app常用API的详细语法知识点(上)(5)
uni-app常用API的详细语法知识点(上)
一、计时器 API
1. 设置计时器:uni.setInterval
/ uni.setTimeout
注意:uni-app 中推荐使用
uni.setInterval
和uni.setTimeout
,而非原生setInterval
,以确保在小程序等平台兼容性。
语法说明:
uni.setInterval(callback, delay)
:每隔delay
毫秒执行一次callback
uni.setTimeout(callback, delay)
:延迟delay
毫秒后执行一次callback
- 返回值为定时器 ID(数字)
示例代码:
<template><view class="timer-demo"><text>倒计时:{{ count }} 秒</text><button @click="startTimer">开始倒计时</button><button @click="clearTimer">取消计时器</button></view>
</template><script>
export default {data() {return {count: 10,timerId: null};},methods: {startTimer() {// 防止重复启动if (this.timerId) return;this.timerId = uni.setInterval(() => {this.count--;if (this.count <= 0) {uni.showToast({ title: '倒计时结束!', icon: 'none' });this.clearTimer();}}, 1000);},clearTimer() {if (this.timerId) {uni.clearInterval(this.timerId); // 取消定时器this.timerId = null;}}},// 页面销毁时务必清除定时器,防止内存泄漏onUnload() {this.clearTimer();}
};
</script>
二、交互反馈 API
1. 信息提示框:uni.showToast
uni.showToast({title: '操作成功',icon: 'success', // 可选:success / error / none / loadingduration: 2000 // 持续时间(毫秒)
});
2. Loading 提示框:uni.showLoading
/ uni.hideLoading
uni.showLoading({ title: '加载中...' });
setTimeout(() => {uni.hideLoading(); // 手动关闭
}, 1500);
3. 模态框:uni.showModal
uni.showModal({title: '确认',content: '是否删除该条记录?',success: (res) => {if (res.confirm) {console.log('用户点击确定');} else if (res.cancel) {console.log('用户点击取消');}}
});
4. 操作菜单:uni.showActionSheet
uni.showActionSheet({itemList: ['拍照', '从相册选择', '取消'],success: (res) => {const index = res.tapIndex;if (index === 0) {console.log('选择拍照');} else if (index === 1) {console.log('选择相册');}// index === 2 为“取消”,通常无需处理},fail: (err) => {console.error('操作菜单调用失败', err);}
});
三、网络请求 API
1. uni.request
:发起 HTTP 请求
语法要点:
- 支持 Promise 和 Callback 两种风格(推荐 Promise + async/await)
success
回调中res.data
为后端返回的业务数据- 需在
manifest.json
中配置合法域名(小程序/H5)
示例代码(Promise 风格):
async function fetchUserData() {uni.showLoading({ title: '获取用户信息...' });try {const res = await uni.request({url: 'https://jsonplaceholder.typicode.com/users/1',method: 'GET',header: {'Content-Type': 'application/json'}});// res.statusCode: HTTP 状态码(如 200)// res.data: 后端返回的 JSON 数据console.log('用户数据:', res.data);uni.showToast({ title: '加载成功', icon: 'success' });} catch (err) {console.error('请求失败:', err);uni.showToast({ title: '网络错误', icon: 'none' });} finally {uni.hideLoading();}
}
Success 回调参数说明:
res.statusCode
:HTTP 状态码(如 200、404)res.data
:服务器返回的数据(自动解析 JSON)res.header
:响应头
2. 上传文件:uni.uploadFile
uni.chooseImage({count: 1,success: (chooseRes) => {const tempFilePath = chooseRes.tempFilePaths[0];uni.uploadFile({url: 'https://api.example.com/upload',filePath: tempFilePath,name: 'file', // 后端接收字段名formData: { userId: '123' }, // 额外参数success: (uploadRes) => {console.log('上传成功', uploadRes.data);uni.showToast({ title: '上传成功' });},fail: (err) => {console.error('上传失败', err);uni.showToast({ title: '上传失败', icon: 'none' });}});}
});
四、数据缓存 API
1. 存储数据:uni.setStorage
/ uni.setStorageSync
// 异步存储
uni.setStorage({key: 'userInfo',data: { name: '张三', age: 25 },success: () => {console.log('数据已保存');}
});// 同步存储(推荐用于简单场景)
uni.setStorageSync('token', 'abc123xyz');
2. 获取数据:uni.getStorage
/ uni.getStorageSync
// 异步获取
uni.getStorage({key: 'userInfo',success: (res) => {console.log('用户信息:', res.data); // { name: '张三', age: 25 }}
});// 同步获取
const token = uni.getStorageSync('token');
console.log('Token:', token);
3. 清理缓存:uni.removeStorage
/ uni.clearStorage
// 删除指定 key
uni.removeStorage({ key: 'userInfo' });// 清空所有缓存(谨慎使用)
uni.clearStorage();
注意:缓存数据在小程序中受平台限制(如微信小程序上限 10MB),H5 中为 localStorage。
五、路由与数据传递
1. 路由跳转 API
API | 说明 |
---|---|
uni.navigateTo | 保留当前页,跳转到新页面(可返回) |
uni.redirectTo | 关闭当前页,跳转到新页面 |
uni.switchTab | 跳转到 tabBar 页面 |
uni.navigateBack | 返回上一页 |
示例:跳转并传参
// 页面 A:跳转到详情页并传递参数
uni.navigateTo({url: '/pages/detail/detail?id=1001&title=Hello'
});
页面 B(detail.vue):接收参数
export default {onLoad(options) {// options 为 URL 中的查询参数console.log('接收到参数:', options); // { id: '1001', title: 'Hello' }this.id = options.id;this.title = decodeURIComponent(options.title); // 如含中文需解码}
};
注意:参数值会自动 URL 编码,若含中文或特殊字符,建议使用
encodeURIComponent
编码,接收时用decodeURIComponent
解码。
六、综合性案例:智云翻译
功能:输入中文,调用免费翻译 API(如百度/腾讯/有道),返回英文结果,并缓存历史记录。
1. 页面结构(translate.vue)
<template><view class="translate-page"><view class="input-area"><textarea v-model="inputText" placeholder="请输入要翻译的中文..." maxlength="200"/><button @click="translate" :disabled="!inputText.trim()">翻译</button></view><view v-if="result" class="result-area"><text class="label">翻译结果:</text><text class="result">{{ result }}</text></view><view class="history"><text>历史记录:</text><view v-for="(item, index) in historyList" :key="index" class="history-item">{{ item.input }} → {{ item.output }}</view></view></view>
</template>
2. 逻辑实现(script 部分)
<script>
export default {data() {return {inputText: '',result: '',historyList: []};},onLoad() {// 从缓存加载历史记录const saved = uni.getStorageSync('translateHistory');if (saved) {this.historyList = saved;}},methods: {async translate() {const text = this.inputText.trim();if (!text) return;uni.showLoading({ title: '翻译中...' });try {// 使用免费测试接口(实际项目应替换为正式 API)const res = await uni.request({url: 'https://api.qiu.finance/translate', // 示例接口(非真实)method: 'POST',data: {q: text,from: 'zh',to: 'en'},header: { 'Content-Type': 'application/json' }});// 假设返回格式:{ code: 200, data: { dst: 'hello world' } }if (res.data.code === 200) {this.result = res.data.data.dst;// 保存到历史记录(最多10条)this.historyList.unshift({ input: text, output: this.result });if (this.historyList.length > 10) {this.historyList.pop();}uni.setStorageSync('translateHistory', this.historyList);} else {throw new Error(res.data.msg || '翻译失败');}} catch (err) {console.error('翻译错误:', err);uni.showToast({ title: '翻译失败,请重试', icon: 'none' });this.result = '';} finally {uni.hideLoading();}}}
};
</script>
3. 样式(可选)
<style>
.translate-page {padding: 30rpx;
}
.input-area {margin-bottom: 40rpx;
}
textarea {width: 100%;height: 200rpx;border: 1rpx solid #ddd;padding: 20rpx;border-radius: 10rpx;margin-bottom: 20rpx;
}
.result-area {background: #f0f9ff;padding: 20rpx;border-radius: 10rpx;margin-bottom: 30rpx;
}
.label {font-weight: bold;color: #1890ff;
}
.history-item {padding: 10rpx 0;border-bottom: 1rpx solid #eee;
}
</style>
说明:实际开发中需申请翻译 API(如百度翻译开放平台),并配置 HTTPS 域名。本例使用模拟逻辑,重点展示 API 组合使用。
本章小结
- 计时器:使用
uni.setInterval
/setTimeout
实现定时任务,注意页面销毁时清除。 - 交互反馈:通过
showToast
、showModal
等提升用户体验。 - 网络请求:
uni.request
是核心,支持 Promise,需处理成功/失败逻辑。 - 数据缓存:
setStorage
/getStorage
实现本地持久化,适用于 Token、用户配置等。 - 路由跳转:
navigateTo
传参通过 URL 查询字符串,onLoad
接收。 - 综合应用:通过“智云翻译”案例,整合网络、缓存、交互、路由等能力,体现 uni-app 多端开发优势。
掌握这些 API,即可构建功能完整的跨平台应用。建议结合
uniCloud
云开发进一步简化后端逻辑。