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(数字)
示例代码:
vue 复制代码
<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

js 复制代码
uni.showToast({
  title: '操作成功',
  icon: 'success', // 可选:success / error / none / loading
  duration: 2000 // 持续时间(毫秒)
});

2. Loading 提示框:uni.showLoading / uni.hideLoading

js 复制代码
uni.showLoading({ title: '加载中...' });
setTimeout(() => {
  uni.hideLoading(); // 手动关闭
}, 1500);

3. 模态框:uni.showModal

js 复制代码
uni.showModal({
  title: '确认',
  content: '是否删除该条记录?',
  success: (res) => {
    if (res.confirm) {
      console.log('用户点击确定');
    } else if (res.cancel) {
      console.log('用户点击取消');
    }
  }
});

4. 操作菜单:uni.showActionSheet

js 复制代码
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 风格):
js 复制代码
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

js 复制代码
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

js 复制代码
// 异步存储
uni.setStorage({
  key: 'userInfo',
  data: { name: '张三', age: 25 },
  success: () => {
    console.log('数据已保存');
  }
});

// 同步存储(推荐用于简单场景)
uni.setStorageSync('token', 'abc123xyz');

2. 获取数据:uni.getStorage / uni.getStorageSync

js 复制代码
// 异步获取
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

js 复制代码
// 删除指定 key
uni.removeStorage({ key: 'userInfo' });

// 清空所有缓存(谨慎使用)
uni.clearStorage();

注意:缓存数据在小程序中受平台限制(如微信小程序上限 10MB),H5 中为 localStorage。


五、路由与数据传递

1. 路由跳转 API

API 说明
uni.navigateTo 保留当前页,跳转到新页面(可返回)
uni.redirectTo 关闭当前页,跳转到新页面
uni.switchTab 跳转到 tabBar 页面
uni.navigateBack 返回上一页
示例:跳转并传参
js 复制代码
// 页面 A:跳转到详情页并传递参数
uni.navigateTo({
  url: '/pages/detail/detail?id=1001&title=Hello'
});
页面 B(detail.vue):接收参数
js 复制代码
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)

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 部分)

vue 复制代码
<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. 样式(可选)

vue 复制代码
<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 云开发进一步简化后端逻辑。

相关推荐
Strawberry965 小时前
chooseVideo传视频无法取到缩略图
微信小程序
林恒smileZAZ5 小时前
CSS3 超实用属性:pointer-events (可穿透图层的鼠标事件)
前端·计算机外设·css3
电子云与长程纠缠5 小时前
UE5 C++ CVar控制台命令字段使用
c++·学习·ue5
云中雾丽5 小时前
flutter中 NotificationListener 详细使用指南
前端
大杯咖啡5 小时前
一篇文章搞懂,浏览器强缓存以及协商缓存
前端·javascript
王六岁6 小时前
# 🐍 前端开发 0 基础学 Python 入门指南: Python 元组和映射类型深入指南
前端·javascript·python
_志哥_6 小时前
多行文本超出,中间显示省略号的终极方法(适配多语言)
前端·javascript·vue.js
王六岁6 小时前
# 🐍 前端开发 0 基础学 Python 入门指南:常用的数据类型和列表
前端·javascript·python
1_2_3_6 小时前
神级JS API,谁用谁好用
前端·javascript