微信小程序开发实践

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

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天前
|
JavaScript API iOS开发
DeepSeek Harness下载、安装、配置一篇搞定(2026整理,送常用插件)
DeepSeek Harness(DSH)是DeepSeek于2026年开源的MIT协议AI Agent框架,支持插件化组装模型、工具、沙箱与UI,兼容主流大模型。本文提供免Node.js的桌面端安装包(Win/macOS),含详细图文教程及热门插件推荐。
|
17天前
|
JSON 程序员 数据格式
最新版Notepad++下载、安装、配置保姆级教程(附官网安装包)
Notepad++ 是一款免费开源、轻量快速的 Windows 文本编辑器,支持多标签、语法高亮、代码折叠与宏录制,体积小、启动快、资源占用低,兼容 x64/x32/ARM 架构,是程序员和文字工作者的高效利器。
4027 1
|
10天前
|
JavaScript 安全 前端开发
Nodejs Brotli decoder 代码执行漏洞 (CVE-2026-111497)10629
Node.js发布安全更新修复Brotli解码器高危RCE漏洞(CVE-2026-111497),建议受影响版本用户立即升级。
2064 2
|
16天前
|
人工智能 API 开发工具
DeepSeek Harness 神插件:白嫖 13 家大厂模型
`dsh-our-free-model` 是 DeepSeek Harness 神级插件:零配置、零API Key、零账号,聚合13家大厂免费模型(含DeepSeek V4.1 Flash、Kimi K3等),支持本地网关、用量看板与自动降级,真正实现“白嫖即用”。
2670 47
|
3天前
|
iOS开发 Docker MacOS
【2026实测】Docker Desktop下载、安装、汉化、配置教程(附官网安装包)
Docker Desktop 是 Docker 官方推出的桌面容器管理工具,集成引擎、CLI、图形界面与 Kubernetes,支持 Win/macOS/Linux。2026 最新版 4.88.1 强化 ARM 原生运行、镜像加速及资源可视化,附中文汉化与国内镜像配置指南。
567 1
|
13天前
|
Web App开发 人工智能 前端开发
2026 年 AI 浏览器怎么选?Ego Lite、Tabbit、Chrome DevTools MCP 深度对比,开发者到底该用哪个?
2026年AI浏览器选型指南:Ego Lite专注多Agent协同(Mac优先),Tabbit国产首选,原生支持Windows与Codex控制;Chrome DevTools MCP非浏览器而是开发者利器,深度集成Console/Network/Performance调试能力,让AI真正“看懂并验证”前端代码。
1520 3
|
10天前
|
开发者 索引
DeepSeekHarness大肥鱼自带插件市场了?加个地址就能用
Open Plugin Market 是一个开放插件索引平台,收录800+优质DSH插件,支持分类浏览、智能推荐与随机发现。无需安装市场,粘贴索引地址即可一键接入,网页版直访 dshopen.org,助力小开发者被看见。(239字)
2113 1
DeepSeekHarness大肥鱼自带插件市场了?加个地址就能用
|
8天前
|
人工智能 Linux API
Magpie, 轻量本地AI网关!免费Token用不完!
Magpie 是开源AI编程模型调度网关,上线一月获1.8万Star。它通过本地高性能网关统一托管多平台API密钥、账号与免费额度,实现跨Agent的模型秒级切换、静默额度轮换与资源复用,显著降低碎片化管理成本。(239字)
Magpie, 轻量本地AI网关!免费Token用不完!

热门文章

最新文章