微信小程序开发入门教程 — 移动端开发

适用人群:前端开发者、想做移动端的开发者
学习时长:约3-5天(每天4小时)
技术栈:微信原生 / uni-app / Taro
适用场景:小程序开发、移动端H5、APP开发

一、微信小程序是什么?

微信小程序是运行在微信内的轻量级应用,无需下载安装,即用即走。

特点说明
用户规模微信月活13亿+
开发成本比APP低70%
获取用户扫码/搜索/分享,获客成本低
适用场景电商、工具、服务、内容

二、开发环境搭建

2.1 注册小程序

1. 访问 https://mp.weixin.qq.com/
2. 注册小程序账号
3. 获取AppID
4. 下载微信开发者工具

2.2 创建项目

# 使用uni-app(推荐,可同时生成小程序/H5/APP)
npx degit dcloudio/uni-preset-vue#vite my-miniapp
cd my-miniapp
npm install
npm run dev:mp-weixin


三、小程序基础

3.1 项目结构

my-miniapp/
├── pages/                  # 页面
│   ├── index/              # 首页
│   │   ├── index.wxml      # 模板(类似HTML)
│   │   ├── index.wxss      # 样式(类似CSS)
│   │   ├── index.js         # 逻辑
│   │   └── index.json       # 配置
│   └── user/               # 用户页
├── components/             # 组件
├── static/                 # 静态资源
├── utils/                  # 工具函数
├── app.js                  # 应用入口
├── app.json                # 应用配置
├── app.wxss                # 全局样式
└── project.config.json     # 项目配置

3.2 页面配置

// app.json
{
  "pages": [
    "pages/index/index",
    "pages/user/index",
    "pages/detail/index"
  ],
  "tabBar": {
    "color": "#999",
    "selectedColor": "#1296db",
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "static/icons/home.png",
        "selectedIconPath": "static/icons/home-active.png"
      },
      {
        "pagePath": "pages/user/index",
        "text": "我的",
        "iconPath": "static/icons/user.png",
        "selectedIconPath": "static/icons/user-active.png"
      }
    ]
  },
  "window": {
    "navigationBarTitleText": "我的小程序",
    "navigationBarBackgroundColor": "#1296db",
    "navigationBarTextStyle": "white"
  }
}

3.3 WXML模板

<!-- pages/index/index.wxml -->
<view class="container">
  <!-- 数据绑定 -->
  <text>{{title}}</text>
  <text>计数:{{count}}</text>
  
  <!-- 条件渲染 -->
  <view wx:if="{{isLoggedIn}}">
    <text>欢迎回来,{{username}}</text>
  </view>
  <view wx:else>
    <button bindtap="login">登录</button>
  </view>
  
  <!-- 列表渲染 -->
  <view wx:for="{{users}}" wx:key="id" class="user-item">
    <text>{{index + 1}}. {{item.username}}</text>
    <text>{{item.email}}</text>
  </view>
  
  <!-- 事件绑定 -->
  <button bindtap="increment">+1</button>
  <button bindtap="handleClick" data-id="{{123}}">点击</button>
  
  <!-- 表单 -->
  <input 
    placeholder="请输入用户名" 
    value="{{username}}" 
    bindinput="onInput"
  />
  <input 
    placeholder="请输入密码" 
    password 
    value="{{password}}" 
    bindinput="onPasswordInput"
  />
  <button type="primary" bindtap="submit">提交</button>
</view>

3.4 页面逻辑

// pages/index/index.js
Page({
  data: {
    title: '首页',
    count: 0,
    isLoggedIn: false,
    username: '',
    password: '',
    users: []
  },
  
  onLoad() {
    this.fetchUsers()
  },
  
  // 事件处理
  increment() {
    this.setData({ count: this.data.count + 1 })
  },
  
  handleClick(e) {
    const id = e.currentTarget.dataset.id
    console.log('点击了:', id)
  },
  
  onInput(e) {
    this.setData({ username: e.detail.value })
  },
  
  onPasswordInput(e) {
    this.setData({ password: e.detail.value })
  },
  
  // 登录
  async login() {
    wx.login({
      success: async (res) => {
        const code = res.code
        // 发送code到后端换取token
        const result = await this.request('/api/auth/login', { code })
        this.setData({ isLoggedIn: true, username: result.username })
      }
    })
  },
  
  // 提交表单
  async submit() {
    if (!this.data.username || !this.data.password) {
      wx.showToast({ title: '请填写完整', icon: 'error' })
      return
    }
    
    await this.request('/api/users', {
      username: this.data.username,
      password: this.data.password
    })
    
    wx.showToast({ title: '创建成功', icon: 'success' })
  },
  
  // 获取用户列表
  async fetchUsers() {
    const result = await this.request('/api/users')
    this.setData({ users: result.items })
  },
  
  // 封装请求
  request(url, data = {}, method = 'GET') {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://api.example.com' + url,
        method,
        data,
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: (res) => resolve(res.data),
        fail: (err) => reject(err)
      })
    })
  }
})

3.5 WXSS样式

/* pages/index/index.wxss */
.container {
  padding: 20rpx;
}

.user-item {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  margin-bottom: 20rpx;
  background: #fff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

button {
  margin: 20rpx 0;
}

input {
  border: 1rpx solid #ddd;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
}


四、uni-app 开发(推荐)

4.1 为什么用uni-app?

特点说明
一套代码多端运行小程序、H5、APP
Vue.js语法前端开发者无缝切换
生态丰富插件市场、UI组件库
性能好接近原生性能

4.2 Vue3 + uni-app

<!-- pages/index/index.vue -->
<template>
  <view class="container">
    <text class="title">{{ title }}</text>
    <text class="count">计数:{{ count }}</text>
    
    <button @click="increment">+1</button>
    
    <view v-for="user in users" :key="user.id" class="user-card">
      <text>{{ user.username }}</text>
      <text>{{ user.email }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const title = ref('首页')
const count = ref(0)
const users = ref([])

const increment = () => {
  count.value++
}

const fetchUsers = async () => {
  const res = await uni.request({
    url: 'https://api.example.com/users',
    method: 'GET'
  })
  users.value = res.data.items
}

onMounted(() => {
  fetchUsers()
})
</script>

<style scoped>
.container {
  padding: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.user-card {
  padding: 20rpx;
  margin: 20rpx 0;
  background: #fff;
  border-radius: 10rpx;
}
</style>


五、常用API

// ====================
// 网络请求
// ====================
uni.request({
  url: 'https://api.example.com/data',
  method: 'GET',
  data: { page: 1 },
  header: { 'Authorization': 'Bearer token' },
  success: (res) => console.log(res.data),
  fail: (err) => console.error(err)
})

// ====================
// 本地存储
// ====================
uni.setStorageSync('token', 'abc123')
const token = uni.getStorageSync('token')
uni.removeStorageSync('token')

// ====================
// 路由跳转
// ====================
uni.navigateTo({ url: '/pages/detail/index?id=123' })
uni.redirectTo({ url: '/pages/login/index' })
uni.switchTab({ url: '/pages/index/index' })
uni.navigateBack()

// ====================
// 消息提示
// ====================
uni.showToast({ title: '操作成功', icon: 'success' })
uni.showLoading({ title: '加载中...' })
uni.hideLoading()
uni.showModal({
  title: '提示',
  content: '确定删除?',
  success: (res) => {
    if (res.confirm) console.log('确定')
  }
})

// ====================
// 图片选择
// ====================
uni.chooseImage({
  count: 1,
  success: (res) => {
    const filePath = res.tempFilePaths[0]
    uni.uploadFile({
      url: 'https://api.example.com/upload',
      filePath,
      name: 'file',
      success: (res) => console.log(res.data)
    })
  }
})

// ====================
// 支付
// ====================
uni.requestPayment({
  provider: 'wxpay',
  timeStamp: '...',
  nonceStr: '...',
  package: '...',
  signType: 'MD5',
  paySign: '...',
  success: (res) => console.log('支付成功'),
  fail: (err) => console.error('支付失败')
})


六、常用UI组件库

组件库特点适用场景
uView UI组件最全、文档好通用
uni-ui官方组件库基础组件
Vant Weapp有赞出品电商
ColorUI颜值高视觉优先
# 安装uView
npm install uview-plus


七、发布流程

1. 开发完成 → 微信开发者工具预览
2. 测试 → 真机调试
3. 上传代码 → 版本管理
4. 提交审核 → 等待审核(1-7天)
5. 审核通过 → 发布上线


学习建议

  1. 先学原生小程序,理解基本概念
  2. 再学uni-app,一套代码多端运行
  3. 掌握常用API,网络请求、存储、路由
  4. 使用UI组件库,提高开发效率
  5. 做一个完整项目,如电商小程序

下一步学习

返回首页