Skip to content

uni-app 基础入门

什么是 uni-app?

uni-app 是一个使用 Vue.js 开发所有前端应用的框架,开发者编写一套代码,可发布到 iOS、Android、Web(响应式)、以及各种小程序(微信/支付宝/百度/头条/QQ/快手/钉钉/淘宝)、快应用等多个平台。

核心特性

  • 跨平台:一套代码多端运行
  • 基于 Vue.js:使用熟悉的 Vue 语法
  • 丰富的组件库:内置常用 UI 组件
  • 插件生态:支持丰富的插件扩展

环境搭建

安装 HBuilderX

  1. 访问 HBuilderX 官网 下载
  2. 安装并启动 HBuilderX
  3. 安装 Vue 插件(如未自动安装)

使用 CLI 创建项目

bash
# 全局安装 vue-cli
npm install -g @vue/cli

# 创建 uni-app 项目
vue create -p dcloudio/uni-preset-vue my-project

# 进入项目目录
cd my-project

# 运行到微信小程序
npm run dev:mp-weixin

# 运行到 H5
npm run dev:h5

# 运行到 App
npm run dev:app-plus

项目结构

my-project/
├── pages/              # 页面目录
│   ├── index/
│   │   └── index.vue
│   └── list/
│       └── list.vue
├── components/         # 组件目录
├── static/            # 静态资源
├── App.vue            # 应用入口
├── main.js            # 入口文件
├── manifest.json      # 应用配置
├── pages.json         # 页面路由配置
└── uni.scss           # 全局样式

页面配置

pages.json

json
{
  "pages": [
    {
      "path": "pages/index/index",
      "style": {
        "navigationBarTitleText": "首页"
      }
    },
    {
      "path": "pages/list/list",
      "style": {
        "navigationBarTitleText": "列表页"
      }
    }
  ],
  "globalStyle": {
    "navigationBarTextStyle": "black",
    "navigationBarTitleText": "uni-app",
    "navigationBarBackgroundColor": "#F8F8F8",
    "backgroundColor": "#F8F8F8"
  },
  "tabBar": {
    "color": "#7A7E83",
    "selectedColor": "#3cc51f",
    "borderStyle": "black",
    "backgroundColor": "#ffffff",
    "list": [
      {
        "pagePath": "pages/index/index",
        "iconPath": "static/tab-home.png",
        "selectedIconPath": "static/tab-home-active.png",
        "text": "首页"
      }
    ]
  }
}

基本语法

页面组件

vue
<template>
  <view class="container">
    <text>{{ message }}</text>
    <button @click="handleClick">点击</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello uni-app'
    }
  },
  methods: {
    handleClick() {
      uni.showToast({
        title: '点击成功',
        icon: 'success'
      })
    }
  }
}
</script>

<style>
.container {
  padding: 20px;
}
</style>

条件渲染

vue
<template>
  <view>
    <view v-if="show">显示内容</view>
    <view v-else>隐藏内容</view>
  </view>
</template>

列表渲染

vue
<template>
  <view>
    <view v-for="(item, index) in list" :key="index">
      {{ item.name }}
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      list: [
        { name: '项目1' },
        { name: '项目2' }
      ]
    }
  }
}
</script>

常用 API

网络请求

javascript
// 发起请求
uni.request({
  url: 'https://api.example.com/data',
  method: 'GET',
  data: {
    id: 1
  },
  success: (res) => {
    console.log(res.data);
  },
  fail: (err) => {
    console.error(err);
  }
});

// 使用 async/await
async function fetchData() {
  try {
    const res = await uni.request({
      url: 'https://api.example.com/data'
    });
    console.log(res.data);
  } catch (err) {
    console.error(err);
  }
}

页面导航

javascript
// 跳转到指定页面
uni.navigateTo({
  url: '/pages/detail/detail?id=1'
});

// 重定向到指定页面
uni.redirectTo({
  url: '/pages/login/login'
});

// 返回上一页
uni.navigateBack();

// 跳转到 tabBar 页面
uni.switchTab({
  url: '/pages/index/index'
});

数据存储

javascript
// 存储数据
uni.setStorage({
  key: 'userInfo',
  data: { name: 'John', age: 30 }
});

// 获取数据
uni.getStorage({
  key: 'userInfo',
  success: (res) => {
    console.log(res.data);
  }
});

// 同步方式
uni.setStorageSync('userInfo', { name: 'John' });
const userInfo = uni.getStorageSync('userInfo');

界面交互

javascript
// 显示提示
uni.showToast({
  title: '操作成功',
  icon: 'success',
  duration: 2000
});

// 显示加载
uni.showLoading({
  title: '加载中...'
});

// 隐藏加载
uni.hideLoading();

// 显示模态框
uni.showModal({
  title: '提示',
  content: '确定要删除吗?',
  success: (res) => {
    if (res.confirm) {
      console.log('用户点击确定');
    }
  }
});

组件使用

内置组件

vue
<template>
  <view>
    <!-- 按钮 -->
    <button type="primary">主要按钮</button>
    
    <!-- 输入框 -->
    <input v-model="inputValue" placeholder="请输入" />
    
    <!-- 图片 -->
    <image src="/static/logo.png" mode="aspectFit"></image>
    
    <!-- 滚动视图 -->
    <scroll-view scroll-y>
      <view v-for="item in list" :key="item.id">
        {{ item.name }}
      </view>
    </scroll-view>
  </view>
</template>

自定义组件

vue
<!-- components/my-component.vue -->
<template>
  <view class="my-component">
    <text>{{ title }}</text>
  </view>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: '默认标题'
    }
  }
}
</script>

使用组件:

vue
<template>
  <view>
    <my-component title="自定义标题"></my-component>
  </view>
</template>

<script>
import MyComponent from '@/components/my-component.vue'

export default {
  components: {
    MyComponent
  }
}
</script>

生命周期

vue
<script>
export default {
  onLoad(options) {
    // 页面加载时触发
    console.log('页面加载', options);
  },
  onShow() {
    // 页面显示时触发
    console.log('页面显示');
  },
  onReady() {
    // 页面初次渲染完成时触发
    console.log('页面渲染完成');
  },
  onHide() {
    // 页面隐藏时触发
    console.log('页面隐藏');
  },
  onUnload() {
    // 页面卸载时触发
    console.log('页面卸载');
  }
}
</script>

平台差异处理

javascript
// 条件编译
// #ifdef H5
console.log('H5 平台');
// #endif

// #ifdef MP-WEIXIN
console.log('微信小程序平台');
// #endif

// #ifdef APP-PLUS
console.log('App 平台');
// #endif

最佳实践

  1. 组件化开发:将功能拆分为独立组件
  2. 样式适配:使用 rpx 单位适配不同屏幕
  3. 性能优化:合理使用条件编译,减少包体积
  4. 错误处理:统一处理网络请求错误
  5. 代码规范:遵循 Vue 和 uni-app 编码规范

最后更新:2025年

这是我的个人文档