微信小程序开发实践

简介: 微信小程序开发实践

1、项目文件

json 配置

wxml 模板

wxss 样式

js 脚本逻辑

2、json 配置

project.config.json 项目配置

app.json 全局配置

page.json 页面配置


3、wxml 模板

标签:view

数据绑定:

动态数据 page.data

Mustache 语法

变量:{{key}}

循环:wx:for

条件:wx:if


eg:


// pages/index/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    name: "Tom",
    arr: ["cat", "dog"],
    isLogin: true,
  },
});
<!--pages/index/index.wxml-->
<!-- 变量 -->
<view>{{name}}</view>
<!-- 列表 -->
<view wx:for="{{arr}}" wx:key="{{index}}">
  {{index}} {{item}}
</view>
<!-- 条件 -->
<view wx:if="{{isLogin}}">已登录</view>
<view wx:else>请登录</view>

4、wxss 样式

responsive pixel 宽度以 750rpx 为标准, 以 iphone6 屏幕为测试标准


/* pages/index/index.wxss */
@import "../../style/guide.wxss";
.box {
  width: 200rpx;
  height: 200rpx;
  background-color: #eeeeee;
}

第三方样式库


weui

iview weapp

vant weapp

5、js 脚本逻辑

<!--pages/index/index.wxml-->
<view>{{count}}</view>
<button bindtap="handleButtonTap" data-id="666" size="mini">点击</button>
// pages/index/index.js
Page({
  handleButtonTap: function (event) {
    console.log(event);
    // 更新数据
    this.setData({
      count: this.data.count + 1,
    });
  },
});

云开发

云函数

获取 appid

获取 openid

生成分享图

调用腾讯云 SDK

云数据库

数据增删改查

云存储

管理文件

上传文件

下载文件

分享文件

Serverless


云数据库

MongoBD

权限管理


示例:


// /pages/about/about.js
// 初始化云数据库
const db = wx.cloud.database();
// 添加数据
handleInsert: function(){
  db.collection('data').add({
    data: {
      name: 'Tom'
    }
  }).then(res=>{
    console.log(res)
  }).catch(err=>{
    console.log(err)
  })
},
// 更新数据
handleUpdate: function () {
  db.collection('data').doc('a9bfcffc5eb78e810058cf6f4b4a03c5').update({
    data: {
      age: 20
    }
  }).then(res => {
    console.log(res)
  }).catch(err => {
    console.log(err)
  })
},
// 查找数据
handleFind: function () {
  db.collection('data').where({
    name: 'Tom'
  }).get().then(res => {
    console.log(res)
  }).catch(err => {
    console.log(err)
  })
},
// 移除数据
handleRemove: function () {
  db.collection('data').doc('a9bfcffc5eb78e810058cf6f4b4a03c5').remove().then(res => {
    console.log(res)
  }).catch(err => {
    console.log(err)
  })
},

云函数

开发环境需要安装Node.js


node -v
v10.16.0

如果提示没有安装


npm install --save wx-server-sdk@latest

云函数求和


// cloudfunctions/sum/index.js
// 云函数 求和
exports.main = async (event, context) => {
  return event.a + event.b;
}

使用云函数


// /pages/about/about.js
handleCallFunc: function() {
    wx.cloud.callFunction({
      name: 'sum',
      data: {
        a: 2,
        b: 3
      }
    }).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
  },

获取openid


// /pages/about/about.js
handleLoing: function(){
    wx.cloud.callFunction({
      name: 'login'
    }).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
  }

批量删除


// cloudfunctions/batchDelete/index.js
// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
// 云函数入口函数
exports.main = async (event, context) => {
  return await db.collection('data').where({
    name: 'Tom'
  }).remove()
}
// /pages/about/about.js
handleBatchDelete: function () {
    wx.cloud.callFunction({
      name: 'batchDelete'
    }).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })
  },

云存储

图片上传


handleUploadFile: function(){
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths
        console.log(tempFilePaths)
        // 上传图片
        wx.cloud.uploadFile({
          // 上传至云端的路径
          cloudPath: new Date().getTime() + '.png', 
          filePath: tempFilePaths[0], // 小程序临时文件路径
          success: res => {
            // 返回文件 ID
            const fileID = res.fileID
            // 存储文件路径
            db.collection('files').add({
              data:{
                fileID: fileID
              }
            }).then(res=>{
              console.log(res)
            }).catch(err=>{
              console.log(err)
            })
          },
          fail: console.error
        })
      }
    })
  }

图片显示和下载


<block wx:for="{{images}}" wx:key="index">
  <image src="{{item.fileID}}"></image>
  <view>
    <button data-fileid="{{item.fileID}}" bindtap="handleDownloadFile">下载图片</button>
  </view>
</block>
// pages/about/about.js
// 初始化云数据库
const db = wx.cloud.database();
Page({
  data: {
    images: []
  },
 getFileList: function() {
    // 获取图片列表
    wx.cloud.callFunction({
      name: 'login',
    }).then(res => {
      db.collection('files').where({
        _openid: res.result.openid
      }).get().then(res => {
        console.log(res)
        this.setData({
          images: res.data
        })
      })
    })
  },
  handleDownloadFile: function(event) {
    // 下载文件
    console.log(event.target.dataset.fileid)
    wx.cloud.downloadFile({
      fileID: event.target.dataset.fileid, // 文件 ID
      success: res => {
        // 返回临时文件路径
        console.log(res.tempFilePath)
        // 保存图片到相册
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success(res) { 
            wx.showToast({
              title: '保存成功',
            })
          }
        })
      },
      fail: console.error
    })
  }
})

电影评分示例

引入Vant Weapp

参考 https://youzan.github.io/vant-weapp/#/quickstart


在 miniprogram 目录下


npm i @vant/weapp -S --production

工具设置

工具 -> 构建 npm

详情 -> 勾选 使用 npm 模块


发送请求

小程序端 需要icp备案

云函数 无需备案


request库

豆瓣电影

电影列表API:

http://api.douban.com/v2/movie/in_theaters?apikey=0df993c66c0c636e29ecbb5344252a4a&start=0&count=10`


代码地址:

https://github.com/mouday/weixin-app-demo


相关文章
|
3天前
|
人工智能 JSON 供应链
畅用7个月无影 JVS Claw |手把手教你把JVS改造成「科研与产业地理情报可视化大师」
LucianaiB分享零成本畅用JVS Claw教程(学生认证享7个月使用权),并开源GeoMind项目——将JVS改造为科研与产业地理情报可视化AI助手,支持飞书文档解析、地理编码与腾讯地图可视化,助力产业关系图谱构建。
23298 2
畅用7个月无影 JVS Claw |手把手教你把JVS改造成「科研与产业地理情报可视化大师」
|
5天前
|
人工智能 API 开发工具
Claude Code国内安装:2026最新保姆教程(附cc-switch配置)
Claude Code是我目前最推荐的AI编程工具,没有之一。 它可能不是最简单的,但绝对是上限最高的。一旦跑通安装、接上模型、定好规范,你会发现很多原本需要几小时的工作,现在几分钟就能搞定。 这套方案的核心优势就三个字:可控性。你不用依赖任何不稳定服务,所有组件都在自己手里。模型效果不好?换一个。框架更新了?自己决定升不升。 这才是AI时代开发者该有的姿势——不是被动等喂饭,而是主动搭建自己的生产力基础设施。 希望这篇保姆教程,能帮你顺利上车。做出你自己的作品。
8084 18
Claude Code国内安装:2026最新保姆教程(附cc-switch配置)
|
13天前
|
缓存 人工智能 自然语言处理
我对比了8个Claude API中转站,踩了不少坑,总结给你
本文是个人开发者耗时1周实测的8大Claude中转平台横向评测,聚焦Claude Code真实体验:以加权均价(¥/M token)、内部汇率、缓存支持、模型真实性及稳定性为核心指标。
4765 24
|
8天前
|
人工智能 JSON BI
DeepSeek V4 来了!超越 Claude Sonnet 4.5,赶紧对接 Claude Code 体验一把
JeecgBoot AI专题研究 把 Claude Code 接入 DeepSeek V4Pro 的真实体验与避坑记录 本文记录我将 Claude Code 对接 DeepSeek 最新模型(V4Pro)后的真实体验,测试了 Skills 自动化查询和积木报表 AI 建表两个场景——有惊喜,也踩
3349 11
|
7天前
|
人工智能 缓存 BI
Claude Code + DeepSeek V4-Pro 真实评测:除了贵,没别的毛病
JeecgBoot AI专题研究 把 Claude Code 接入 DeepSeek V4Pro,跑完 Skills —— OA 审批、大屏、报表、部署 5 大实战场景后的真实体验 ![](https://oscimg.oschina.net/oscnet/up608d34aeb6bafc47f
2725 9
Claude Code + DeepSeek V4-Pro 真实评测:除了贵,没别的毛病
|
25天前
|
人工智能 自然语言处理 安全
Claude Code 全攻略:命令大全 + 实战工作流(建议收藏)
本文介绍了Claude Code终端AI助手的使用指南,主要内容包括:1)常用命令如版本查看、项目启动和更新;2)三种工作模式切换及界面说明;3)核心功能指令速查表,包含初始化、压缩对话、清除历史等操作;4)详细解析了/init、/help、/clear、/compact、/memory等关键命令的使用场景和语法。文章通过丰富的界面截图和场景示例,帮助开发者快速掌握如何通过命令行和交互界面高效使用Claude Code进行项目开发,特别强调了CLAUDE.md文件作为项目知识库的核心作用。
20412 62
Claude Code 全攻略:命令大全 + 实战工作流(建议收藏)