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

uni-app 入门学习教程,从入门到精通, uni-app常用API的详细语法知识点(上)(5)

uni-app常用API的详细语法知识点(上)


一、计时器 API

1. 设置计时器:uni.setInterval / uni.setTimeout

注意:uni-app 中推荐使用 uni.setIntervaluni.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 实现定时任务,注意页面销毁时清除。
  • 交互反馈:通过 showToastshowModal 等提升用户体验。
  • 网络请求uni.request 是核心,支持 Promise,需处理成功/失败逻辑。
  • 数据缓存setStorage/getStorage 实现本地持久化,适用于 Token、用户配置等。
  • 路由跳转navigateTo 传参通过 URL 查询字符串,onLoad 接收。
  • 综合应用:通过“智云翻译”案例,整合网络、缓存、交互、路由等能力,体现 uni-app 多端开发优势。

掌握这些 API,即可构建功能完整的跨平台应用。建议结合 uniCloud 云开发进一步简化后端逻辑。

http://www.dtcms.com/a/503490.html

相关文章:

  • 设计模式篇之 访问者模式 Visitor
  • 疾控网站建设宗旨和目的wordpress设置为繁体字
  • 免费视频素材网站有哪些游戏制作公司
  • 09_Windows平台Redis开发环境配置完整指南
  • 小谈:数据地图在制造企业的应用
  • 网站建设行业分析报告学校为什么要做网站
  • 手机特殊网站wordpress 环境
  • 使用Linux系统函数递归遍历指定目录
  • h5游戏免费下载:龟兔再跑
  • opendds初入门之qos策略初了解(有遗留)
  • 多视图几何--立体匹配--Gipuma
  • C++智能指针全面解析:原理、使用场景与最佳实践
  • C++指针使用
  • 内江规划建设教育网站国家企业信用公示信息网官网
  • 深入理解 lscpu 命令:如何准确查看 CPU 信息
  • 网站建设需要什么人希腊网站后缀
  • DSync for Mac 文件对比同步工具
  • 「日拱一码」123 内嵌神经网络ENNs
  • C++与易语言开发的基础要求分享
  • 上海市住宅建设发展中心网站建设网站有何要求
  • 广州企业网站建设公司哪家好wordpress改html5
  • ARM 架构核心知识笔记(整理与补充版)
  • 《i.MX6ULL LED 裸机开发实战:从寄存器到点亮》
  • 迈向零信任存储:基于RustFS构建内生安全的数据架构
  • 网站开发公司找哪家帮卖货平台
  • C++ Vector:动态数组的高效使用指南
  • html5微网站漂亮网站
  • C++ 分配内存 new/malloc 区别
  • Respective英文单词学习
  • 网络排错全流程:从DNS解析到防火墙,逐层拆解常见问题