uni-app开发微信小程序

本文涉及的产品
Serverless 应用引擎 SAE,800核*时 1600GiB*时
可观测监控 Prometheus 版,每月50GB免费额度
容器服务 Serverless 版 ACK Serverless,317元额度 多规格
简介: 本文详细介绍如何使用 uni-app 开发微信小程序,涵盖需求分析、架构思路及实施方案。主要功能包括用户登录、商品列表展示、商品详情、购物车及订单管理。技术栈采用 uni-app、uView UI 和 RESTful API。文章通过具体示例代码展示了从初始化项目、配置全局样式到实现各页面组件及 API 接口的全过程,并提供了完整的文件结构和配置文件示例。此外,还介绍了微信授权登录及后端接口模拟方法,确保项目的稳定性和安全性。通过本教程,读者可快速掌握使用 uni-app 开发微信小程序的方法。

1. 需求分析

随着移动互联网的发展,微信小程序已经成为了一种非常流行的应用形式。uni-app 是一种使用 Vue.js 开发所有前端应用的框架,它支持一次开发多端部署,包括微信小程序、H5、App 等。本文将详细介绍如何使用 uni-app 开发微信小程序,并通过一个简单的示例来展示整个开发过程。
image.png

主要需求点

  • 用户登录:支持微信授权登录。
  • 商品列表:展示商品信息。
  • 商品详情:展示商品详情信息。
  • 购物车功能:用户可以将商品加入购物车。
  • 订单功能:用户可以提交订单并查看订单状态。

2. 架构思路

技术栈

  • 前端框架:uni-app
  • UI库:uView UI
  • 后端接口:基于 RESTful API 的接口

核心组件

  • 页面组件:首页、商品列表页、商品详情页、购物车页、订单页。
  • API接口:获取商品列表、获取商品详情、添加商品到购物车、提交订单等。
  • 状态管理:使用 Vuex 管理全局状态。
  • 路由管理:使用 Vue Router 管理页面路由。

3. 实施方案

步骤一:初始化项目

  1. 安装 Node.js 和 HBuilderX。
  2. 使用 HBuilderX 创建一个 uni-app 项目。
npm install -g @dcloudio/uni-cli
uni init myApp
cd myApp
npm install

步骤二:安装 uView UI

npm install uview-ui --save

步骤三:配置全局样式

main.js 中引入 uView UI:

import uView from 'uview-ui';
Vue.use(uView);

步骤四:创建页面组件

  1. 首页:展示商品列表。
  2. 商品列表页:展示商品列表。
  3. 商品详情页:展示商品详情信息。
  4. 购物车页:展示购物车中的商品。
  5. 订单页:展示订单信息。

步骤五:实现 API 接口

  1. 获取商品列表/api/products
  2. 获取商品详情/api/products/:id
  3. 添加商品到购物车/api/cart
  4. 提交订单/api/orders

步骤六:实现页面逻辑

  1. 首页:展示商品列表。
  2. 商品列表页:获取商品列表并展示。
  3. 商品详情页:获取商品详情并展示。
  4. 购物车页:展示购物车中的商品。
  5. 订单页:展示订单信息。

4. 案例分享

示例代码

文件结构

├── pages/
│   ├── index/
│   │   ├── index.vue
│   │   └── index.json
│   ├── products/
│   │   ├── products.vue
│   │   └── products.json
│   ├── product-detail/
│   │   ├── product-detail.vue
│   │   └── product-detail.json
│   ├── cart/
│   │   ├── cart.vue
│   │   └── cart.json
│   └── orders/
│       ├── orders.vue
│       └── orders.json
├── static/
├── components/
├── common/
├── store/
├── main.js
└── app.json

页面组件

首页 index/index.vue

<template>
  <view class="container">
    <view class="title">商品列表</view>
    <u-cell-group>
      <u-cell-item v-for="product in products" :key="product.id" @click="goToProductDetail(product)">
        {
  
  { product.name }}
      </u-cell-item>
    </u-cell-group>
  </view>
</template>

<script>
export default {
  data() {
    return {
      products: []
    };
  },
  onLoad() {
    this.fetchProducts();
  },
  methods: {
    async fetchProducts() {
      const response = await this.$http.get('/api/products');
      this.products = response.data;
    },
    goToProductDetail(product) {
      uni.navigateTo({
        url: `/pages/product-detail/product-detail?id=${product.id}`
      });
    }
  }
};
</script>

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

.title {
  font-size: 20px;
  margin-bottom: 10px;
}
</style>

商品列表页 products/products.vue

<template>
  <view class="container">
    <view class="title">商品列表</view>
    <u-list>
      <u-list-item v-for="product in products" :key="product.id" @click="goToProductDetail(product)">
        <view slot="title">{
  
  { product.name }}</view>
        <view slot="desc">价格:{
  
  { product.price }}元</view>
      </u-list-item>
    </u-list>
  </view>
</template>

<script>
export default {
  data() {
    return {
      products: []
    };
  },
  onLoad() {
    this.fetchProducts();
  },
  methods: {
    async fetchProducts() {
      const response = await this.$http.get('/api/products');
      this.products = response.data;
    },
    goToProductDetail(product) {
      uni.navigateTo({
        url: `/pages/product-detail/product-detail?id=${product.id}`
      });
    }
  }
};
</script>

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

.title {
  font-size: 20px;
  margin-bottom: 10px;
}
</style>

商品详情页 product-detail/product-detail.vue

<template>
  <view class="container">
    <view class="title">{
  
  { product.name }}</view>
    <view class="details">
      <view>价格:{
  
  { product.price }}元</view>
      <view>描述:{
  
  { product.description }}</view>
      <u-button type="primary" @click="addToCart">加入购物车</u-button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      product: {}
    };
  },
  onLoad(options) {
    this.fetchProduct(options.id);
  },
  methods: {
    async fetchProduct(id) {
      const response = await this.$http.get(`/api/products/${id}`);
      this.product = response.data;
    },
    addToCart() {
      this.$store.commit('addProductToCart', this.product);
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      });
    }
  }
};
</script>

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

.title {
  font-size: 20px;
  margin-bottom: 10px;
}

.details {
  margin-top: 10px;
}
</style>

购物车页 cart/cart.vue

<template>
  <view class="container">
    <view class="title">购物车</view>
    <u-list>
      <u-list-item v-for="product in cartItems" :key="product.id">
        <view slot="title">{
  
  { product.name }}</view>
        <view slot="desc">价格:{
  
  { product.price }}元</view>
      </u-list-item>
    </u-list>
    <u-button type="primary" @click="submitOrder">提交订单</u-button>
  </view>
</template>

<script>
export default {
  computed: {
    cartItems() {
      return this.$store.state.cart;
    }
  },
  methods: {
    submitOrder() {
      this.$store.commit('submitOrder');
      uni.showToast({
        title: '订单提交成功',
        icon: 'success'
      });
    }
  }
};
</script>

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

.title {
  font-size: 20px;
  margin-bottom: 10px;
}
</style>

Vuex 状态管理

store/index.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
   
   
  state: {
   
   
    cart: []
  },
  mutations: {
   
   
    addProductToCart(state, product) {
   
   
      state.cart.push(product);
    },
    submitOrder(state) {
   
   
      console.log('Submitting order:', state.cart);
      state.cart = [];
    }
  }
});

API 接口

common/api.js

export default {
   
   
  async getProducts() {
   
   
    const response = await fetch('/api/products');
    return response.json();
  },
  async getProduct(id) {
   
   
    const response = await fetch(`/api/products/${
     
     id}`);
    return response.json();
  }
};

配置文件

app.json

{
   
   
  "pages": [
    "pages/index/index",
    "pages/products/products",
    "pages/product-detail/product-detail",
    "pages/cart/cart",
    "pages/orders/orders"
  ],
  "window": {
   
   
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "微信小程序商城",
    "navigationBarTextStyle": "black"
  },
  "tabBar": {
   
   
    "color": "#7A7E83",
    "selectedColor": "#3cc51f",
    "borderStyle": "black",
    "list": [
      {
   
   
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "static/home.png",
        "selectedIconPath": "static/home_selected.png"
      },
      {
   
   
        "pagePath": "pages/products/products",
        "text": "商品",
        "iconPath": "static/products.png",
        "selectedIconPath": "static/products_selected.png"
      },
      {
   
   
        "pagePath": "pages/cart/cart",
        "text": "购物车",
        "iconPath": "static/cart.png",
        "selectedIconPath": "static/cart_selected.png"
      },
      {
   
   
        "pagePath": "pages/orders/orders",
        "text": "订单",
        "iconPath": "static/orders.png",
        "selectedIconPath": "static/orders_selected.png"
      }
    ]
  },
  "networkTimeout": {
   
   
    "request": 10000,
    "downloadFile": 10000
  },
  "debug": true
}

微信授权登录

common/auth.js

import {
   
    getUserInfo } from '@uni_modules/uni-id-pages/api/user';

export default {
   
   
  async login() {
   
   
    try {
   
   
      const result = await getUserInfo();
      console.log('User info:', result);
      // 可以在这里处理登录后的逻辑,如保存用户信息等
    } catch (error) {
   
   
      console.error('Login error:', error);
    }
  }
};

后端接口模拟

mock/api.js

const products = [
  {
   
   
    id: 1,
    name: '苹果',
    price: 5,
    description: '新鲜水果,口感脆甜。'
  },
  {
   
   
    id: 2,
    name: '香蕉',
    price: 3,
    description: '新鲜水果,口感香甜。'
  },
  {
   
   
    id: 3,
    name: '橙子',
    price: 4,
    description: '新鲜水果,口感酸甜。'
  }
];

export default {
   
   
  async getProducts() {
   
   
    return products;
  },
  async getProduct(id) {
   
   
    return products.find(product => product.id === parseInt(id));
  }
};

集成到项目中

修改 main.js

import Vue from 'vue';
import App from './App.vue';
import uView from 'uview-ui';
import store from './store';
import api from './common/api';
import auth from './common/auth';

Vue.config.productionTip = false;
Vue.prototype.$http = api;
Vue.use(uView);

new Vue({
   
   
  store,
  render: h => h(App)
}).$mount('#app');

// 初始化登录
auth.login();

运行项目

  1. 在 HBuilderX 中打开项目。
  2. 点击编译并预览。
  3. 使用微信开发者工具查看效果。

运行结果

运行上述代码后,可以看到以下效果:

  • 首页展示商品列表。
  • 商品列表页展示商品详细信息,并可以将商品加入购物车。
  • 购物车页展示购物车中的商品,并可以提交订单。
  • 订单页展示订单信息。

5. 注意事项

  1. 权限管理:在使用微信授权登录时,需要确保用户授权信息的安全性。
  2. 网络请求:在实际项目中,需要确保网络请求的稳定性和安全性,建议使用 HTTPS 协议。
  3. 状态管理:使用 Vuex 管理全局状态时,需要注意状态的一致性和同步性。
  4. 路由管理:使用 Vue Router 管理页面路由时,需要确保路由跳转的顺畅性和用户体验。
  5. UI设计:选择合适的 UI 库(如 uView UI)可以大大提高开发效率和界面美观度。

6. 总结

通过本篇博客,我们详细介绍了如何使用 uni-app 开发微信小程序,并通过一个简单的示例展示了整个开发过程。uni-app 的优势在于它可以一次开发多端部署,极大地提高了开发效率。希望这篇博客能帮助你在实际项目中更好地应用 uni-app。

如果你有任何疑问或建议,请随时留言交流。祝你开发顺利!

目录
相关文章
|
15天前
|
Web App开发 Java 视频直播
FFmpeg开发笔记(四十九)助您在毕业设计中脱颖而出的几个流行APP
对于软件、计算机等专业的毕业生,毕业设计需实现实用软件或APP。新颖的设计应结合最新技术,如5G时代的音视频技术。示例包括: 1. **短视频分享APP**: 集成FFmpeg实现视频剪辑功能,如添加字幕、转场特效等。 2. **电商购物APP**: 具备直播带货功能,使用RTMP/SRT协议支持流畅直播体验。 3. **同城生活APP**: 引入WebRTC技术实现可信的视频通话功能。这些应用不仅实用,还能展示开发者紧跟技术潮流的能力。
41 4
FFmpeg开发笔记(四十九)助您在毕业设计中脱颖而出的几个流行APP
|
17天前
|
小程序 前端开发 Java
SpringBoot+uniapp+uview打造H5+小程序+APP入门学习的聊天小项目
JavaDog Chat v1.0.0 是一款基于 SpringBoot、MybatisPlus 和 uniapp 的简易聊天软件,兼容 H5、小程序和 APP,提供丰富的注释和简洁代码,适合初学者。主要功能包括登录注册、消息发送、好友管理及群组交流。
40 0
SpringBoot+uniapp+uview打造H5+小程序+APP入门学习的聊天小项目
|
5天前
|
小程序 开发工具
app跳转微信小程序,使用明文scheme拉起
app跳转微信小程序,使用明文scheme拉起
26 4
|
18天前
|
小程序
Taro@3.x+Vue@3.x+TS开发微信小程序,设置转发分享
本文介绍了Taro中`useShareAppMessage`的使用方法,需在页面配置`enableShareAppMessage: true`并重新编译。
Taro@3.x+Vue@3.x+TS开发微信小程序,设置转发分享
|
8天前
|
小程序 前端开发 JavaScript
开发支付宝小程序的思路
【9月更文挑战第7天】本文介绍了一种在支付宝小程序中实现网页抓取的方法,通过云函数或自建后端服务来解析外部网页的标题、描述和图片。具体步骤包括:用户输入链接,小程序调用云函数抓取并解析网页内容,最后将结果返回并在前端展示。文中详细介绍了使用 Node.js 的云函数实现过程,包括代码示例和小程序前端页面的实现方法。通过这种方式,可以显著提升链接分享的用户体验。
20 0
|
16天前
|
Android开发 iOS开发 C#
Xamarin:用C#打造跨平台移动应用的终极利器——从零开始构建你的第一个iOS与Android通用App,体验前所未有的高效与便捷开发之旅
【8月更文挑战第31天】Xamarin 是一个强大的框架,允许开发者使用单一的 C# 代码库构建高性能的原生移动应用,支持 iOS、Android 和 Windows 平台。作为微软的一部分,Xamarin 充分利用了 .NET 框架的强大功能,提供了丰富的 API 和工具集,简化了跨平台移动应用开发。本文通过一个简单的示例应用介绍了如何使用 Xamarin.Forms 快速创建跨平台应用,包括设置开发环境、定义用户界面和实现按钮点击事件处理逻辑。这个示例展示了 Xamarin.Forms 的基本功能,帮助开发者提高开发效率并实现一致的用户体验。
35 0
|
移动开发 安全 PHP
微信分享和微信H5跳转到APP开放标签wx-open-launch-app使用及样式设置
微信分享和微信H5跳转到APP开放标签wx-open-launch-app使用及样式设置
1427 0
|
移动开发 安全 PHP
微信分享和微信H5跳转到APP开放标签wx-open-launch-app使用及样式设置
微信分享和微信H5跳转到APP开放标签wx-open-launch-app使用及样式设置
857 0
|
30天前
|
Web App开发 Android开发
FFmpeg开发笔记(四十六)利用SRT协议构建手机APP的直播Demo
实时数据传输在互联网中至关重要,不仅支持即时通讯如QQ、微信的文字与图片传输,还包括音视频通信。一对一通信常采用WebRTC技术,如《Android Studio开发实战》中的App集成示例;而一对多的在线直播则需部署独立的流媒体服务器,使用如SRT等协议。SRT因其优越的直播质量正逐渐成为主流。本文档概述了SRT协议的使用,包括通过OBS Studio和SRT Streamer进行SRT直播推流的方法,并展示了推流与拉流的成功实例。更多细节参见《FFmpeg开发实战》一书。
37 1
FFmpeg开发笔记(四十六)利用SRT协议构建手机APP的直播Demo
|
1月前
|
Web App开发 5G Linux
FFmpeg开发笔记(四十四)毕业设计可做的几个拉满颜值的音视频APP
一年一度的毕业季来临,计算机专业的毕业设计尤为重要,不仅关乎学业评价还积累实战经验。选择紧跟5G技术趋势的音视频APP作为课题极具吸引力。这里推荐三类应用:一是融合WebRTC技术实现视频通话的即时通信APP;二是具备在线直播功能的短视频分享平台,涉及RTMP/SRT等直播技术;三是具有自定义动画特效及卡拉OK歌词字幕功能的视频剪辑工具。这些项目不仅技术含量高,也符合市场需求,是毕业设计的理想选择。
60 6
FFmpeg开发笔记(四十四)毕业设计可做的几个拉满颜值的音视频APP