• 小程序实现后台数据交互及WXS的使用


    一,数据交互准备工作

    1.1 后端准备

    后端部分代码,可自行创建后端代码

    1. package com.zking.minoa.wxcontroller;
    2. import com.zking.minoa.mapper.InfoMapper;
    3. import com.zking.minoa.model.Info;
    4. import com.zking.minoa.util.ResponseUtil;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.web.bind.annotation.RequestMapping;
    7. import org.springframework.web.bind.annotation.RestController;
    8. import java.util.HashMap;
    9. import java.util.List;
    10. import java.util.Map;
    11. /**
    12. * @Autho donkee
    13. * @Since 2022/6/29
    14. */
    15. @RestController
    16. @RequestMapping("/wx/home")
    17. public class WxHomeController {
    18. @Autowired
    19. private InfoMapper infoMapper;
    20. @RequestMapping("/index")
    21. public Object index(Info info) {
    22. List infoList = infoMapper.list(info);
    23. Map data = new HashMap();
    24. data.put("infoList",infoList);
    25. return ResponseUtil.ok(data);
    26. }
    27. }

    pom.xml的配置:

    根据自己有更多需求进行应用配置的增加

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <parent>
    6. <groupId>org.springframework.bootgroupId>
    7. <artifactId>spring-boot-starter-parentartifactId>
    8. <version>2.6.2version>
    9. <relativePath/>
    10. parent>
    11. <groupId>com.zkinggroupId>
    12. <artifactId>minoaartifactId>
    13. <version>0.0.1-SNAPSHOTversion>
    14. <name>minoaname>
    15. <description>Demo project for Spring Bootdescription>
    16. <properties>
    17. <java.version>1.8java.version>
    18. <fastjson.version>1.2.70fastjson.version>
    19. <jackson.version>2.9.8jackson.version>
    20. properties>
    21. <dependencies>
    22. <dependency>
    23. <groupId>org.springframework.bootgroupId>
    24. <artifactId>spring-boot-starter-jdbcartifactId>
    25. dependency>
    26. <dependency>
    27. <groupId>org.springframework.bootgroupId>
    28. <artifactId>spring-boot-starter-webartifactId>
    29. dependency>
    30. <dependency>
    31. <groupId>org.mybatis.spring.bootgroupId>
    32. <artifactId>mybatis-spring-boot-starterartifactId>
    33. <version>2.2.1version>
    34. dependency>
    35. <dependency>
    36. <groupId>mysqlgroupId>
    37. <artifactId>mysql-connector-javaartifactId>
    38. <version>5.1.44version>
    39. <scope>runtimescope>
    40. dependency>
    41. <dependency>
    42. <groupId>org.projectlombokgroupId>
    43. <artifactId>lombokartifactId>
    44. <optional>trueoptional>
    45. dependency>
    46. <dependency>
    47. <groupId>com.alibabagroupId>
    48. <artifactId>fastjsonartifactId>
    49. <version>${fastjson.version}version>
    50. dependency>
    51. dependencies>
    52. <build>
    53. <plugins>
    54. <plugin>
    55. <groupId>org.springframework.bootgroupId>
    56. <artifactId>spring-boot-maven-pluginartifactId>
    57. <configuration>
    58. <excludes>
    59. <exclude>
    60. <groupId>org.projectlombokgroupId>
    61. <artifactId>lombokartifactId>
    62. exclude>
    63. excludes>
    64. configuration>
    65. plugin>
    66. <plugin>
    67. <groupId>org.mybatis.generatorgroupId>
    68. <artifactId>mybatis-generator-maven-pluginartifactId>
    69. <version>1.3.2version>
    70. <dependencies>
    71. <dependency>
    72. <groupId>mysqlgroupId>
    73. <artifactId>mysql-connector-javaartifactId>
    74. <version>${mysql.version}version>
    75. dependency>
    76. dependencies>
    77. <configuration>
    78. <overwrite>trueoverwrite>
    79. configuration>
    80. plugin>
    81. plugins>
    82. build>
    83. project>

    访问所有数据 

    1.2 前端工作

     为了后期方便维护,我们先将所有的后端接口通过一个文件来保存,在根目录下新建config文件夹随后建立api.js文件

    1. // 以下是业务服务器API地址
    2. // 本机开发API地址
    3. var WxApiRoot = 'http://localhost:8080/wx/';
    4. // 测试环境部署api地址
    5. // var WxApiRoot = 'http://192.168.0.101:8070/demo/wx/';
    6. // 线上平台api地址
    7. //var WxApiRoot = 'https://www.oa-mini.com/demo/wx/';
    8. module.exports = {
    9. IndexUrl: WxApiRoot + 'home/index', //首页数据接口
    10. SwiperImgs: WxApiRoot+'swiperImgs', //轮播图
    11. MettingInfos: WxApiRoot+'meeting/list', //会议信息
    12. };

    1.2.1请求方式的封装

    1. loadMeetingInfos(){
    2. let that=this;
    3. wx.request({
    4. url: api.IndexUrl,
    5. dataType: 'json',
    6. success(res) {
    7. console.log(res)
    8. that.setData({
    9. lists:res.data.data.infoList
    10. })
    11. }
    12. })
    13. }

    在/utils/util.js中添加下列代码:

    1. /**
    2. * 封装微信的request请求
    3. */
    4. function request(url, data = {}, method = "GET") {
    5. return new Promise(function (resolve, reject) {
    6. wx.request({
    7. url: url,
    8. data: data,
    9. method: method,
    10. header: {
    11. 'Content-Type': 'application/json',
    12. },
    13. success: function (res) {
    14. if (res.statusCode == 200) {
    15. resolve(res.data);//会把进行中改变成已成功
    16. } else {
    17. reject(res.errMsg);//会把进行中改变成已失败
    18. }
    19. },
    20. fail: function (err) {
    21. reject(err)
    22. }
    23. })
    24. });
    25. }

    注意在module.exports中导出和需要使用的页面js中使用时定义:const util = require("../../utils/util")

    1. //首页会议信息的ajax
    2. loadMeetingInfos() {
    3. let that = this;
    4. util.request(api.IndexUrl).then(res => {
    5. this.setData({
    6. lists: res.data.infoList
    7. })
    8. })
    9. }

    二,实现数据交互

    前端wxml:

    1. <view>
    2. <swiper autoplay="true" indicator-dots="true">
    3. <block wx:for="{{imgSrcs}}" wx:key="text">
    4. <swiper-item>
    5. <view>
    6. <image src="{{item.img}}" class="swiper-item" />
    7. view>
    8. swiper-item>
    9. block>
    10. swiper>
    11. view>
    12. <view class="mobi-title">
    13. <text class="mobi-icon">text>
    14. <text class="mobi-text">会议信息text>
    15. view>
    16. <block wx:for-items="{{lists}}" wx:for-item="item" wx:key="item.id">
    17. <view class="list" data-id="{{item.id}}">
    18. <view class="list-img">
    19. <image class="video-img" mode="scaleToFill" src="{{item.image !=null? item.image : '/static/persons/6.png'}}">image>
    20. view>
    21. <view class="list-detail">
    22. <view class="list-title"><text>{{item.title}}text>view>
    23. <view class="list-tag">
    24. <view class="state">{{item.state}}view>
    25. <view class="join"><text class="list-num">{{item.num}}text>人报名view>
    26. view>
    27. <view class="list-info"><text>{{item.location}}text>|<text>{{item.starttime}}text>view>
    28. view>
    29. view>
    30. block>
    31. <view class="section">
    32. <text>到底啦text>
    33. view>

    前端wxss:

    1. /**index.wxss**/
    2. .section{
    3. color: #aaa;
    4. display: flex;
    5. justify-content: center;
    6. }
    7. .list-info {
    8. color: #aaa;
    9. }
    10. .list-num {
    11. color: #e40909;
    12. font-weight: 700;
    13. }
    14. .join {
    15. padding: 0px 0px 0px 10px;
    16. color: #aaa;
    17. }
    18. .state {
    19. margin: 0px 6px 0px 6px;
    20. border: 1px solid #93b9ff;
    21. color: #93b9ff;
    22. }
    23. .list-tag {
    24. padding: 3px 0px 10px 0px;
    25. display: flex;
    26. align-items: center;
    27. }
    28. .list-title {
    29. display: flex;
    30. justify-content: space-between;
    31. font-size: 11pt;
    32. color: #333;
    33. font-weight: bold;
    34. }
    35. .list-detail {
    36. display: flex;
    37. flex-direction: column;
    38. margin: 0px 0px 0px 15px;
    39. }
    40. .video-img {
    41. width: 80px;
    42. height: 80px;
    43. }
    44. .list {
    45. display: flex;
    46. flex-direction: row;
    47. border-bottom: 1px solid #6b6e74;
    48. padding: 10px;
    49. }
    50. .mobi-text {
    51. font-weight: 700;
    52. padding: 15px;
    53. }
    54. .mobi-icon {
    55. border-left: 5px solid #e40909;
    56. }
    57. .mobi-title {
    58. background-color: rgba(158, 158, 142, 0.678);
    59. margin: 10px 0px 10px 0px;
    60. }
    61. .swiper-item {
    62. height: 300rpx;
    63. width: 100%;
    64. border-radius: 10rpx;
    65. }
    66. .userinfo {
    67. display: flex;
    68. flex-direction: column;
    69. align-items: center;
    70. color: #aaa;
    71. }
    72. .userinfo-avatar {
    73. overflow: hidden;
    74. width: 128rpx;
    75. height: 128rpx;
    76. margin: 20rpx;
    77. border-radius: 50%;
    78. }
    79. .usermotto {
    80. margin-top: 200px;
    81. }

    三,WXS的使用

        WXS 代码可以编写在 wxml 文件中的 标签内,或以 .wxs 为后缀名的文件内

    在wxs中,可以使用一些内置的方法和对象来实现数据处理,如Math、Date等。同时,也可以使用一些自定义的函数和变量来实现特定的业务逻辑

    通过后台数据交互和wxs应用,可以实现小程序的数据展示、数据操作和业务逻辑的实现。同时,也可以提高小程序的性能和用户体验

    3.1 WXS文件

    在项目中的utils文件中创建 .wxs 文件,名为: comm.wxs

    comm.wxs代码:

    1. function getState(state){
    2. // 状态:0取消会议1待审核2驳回3待开4进行中5开启投票6结束会议,默认值为1
    3. if(state == 0 ){
    4. return '取消会议';
    5. }else if(state == 1 ){
    6. return '待审核';
    7. }else if(state == 2 ){
    8. return '驳回';
    9. }else if(state == 3 ){
    10. return '待开';
    11. }else if(state == 4 ){
    12. return '进行中';
    13. }else if(state == 5 ){
    14. return '开启投票';
    15. }else if(state == 6 ){
    16. return '结束会议';
    17. }
    18. return '其它';
    19. }
    20. var getNumber = function(str) {
    21. var s = str+'';
    22. var array = s.split(',');
    23. var len = array.length;
    24. return len;
    25. }
    26. function formatDate(ts, option) {
    27. var date = getDate(ts)
    28. var year = date.getFullYear()
    29. var month = date.getMonth() + 1
    30. var day = date.getDate()
    31. var week = date.getDay()
    32. var hour = date.getHours()
    33. var minute = date.getMinutes()
    34. var second = date.getSeconds()
    35. //获取 年月日
    36. if (option == 'YY-MM-DD') return [year, month, day].map(formatNumber).join('-')
    37. //获取 年月
    38. if (option == 'YY-MM') return [year, month].map(formatNumber).join('-')
    39. //获取 年
    40. if (option == 'YY') return [year].map(formatNumber).toString()
    41. //获取 月
    42. if (option == 'MM') return [mont].map(formatNumber).toString()
    43. //获取 日
    44. if (option == 'DD') return [day].map(formatNumber).toString()
    45. //获取 年月日 周一 至 周日
    46. if (option == 'YY-MM-DD Week') return [year, month, day].map(formatNumber).join('-') + ' ' + getWeek(week)
    47. //获取 月日 周一 至 周日
    48. if (option == 'MM-DD Week') return [month, day].map(formatNumber).join('-') + ' ' + getWeek(week)
    49. //获取 周一 至 周日
    50. if (option == 'Week') return getWeek(week)
    51. //获取 时分秒
    52. if (option == 'hh-mm-ss') return [hour, minute, second].map(formatNumber).join(':')
    53. //获取 时分
    54. if (option == 'hh-mm') return [hour, minute].map(formatNumber).join(':')
    55. //获取 分秒
    56. if (option == 'mm-dd') return [minute, second].map(formatNumber).join(':')
    57. //获取 时
    58. if (option == 'hh') return [hour].map(formatNumber).toString()
    59. //获取 分
    60. if (option == 'mm') return [minute].map(formatNumber).toString()
    61. //获取 秒
    62. if (option == 'ss') return [second].map(formatNumber).toString()
    63. //默认 时分秒 年月日
    64. return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
    65. }
    66. function formatNumber(n) {
    67. n = n.toString()
    68. return n[1] ? n : '0' + n
    69. }
    70. function getWeek(n) {
    71. switch(n) {
    72. case 1:
    73. return '星期一'
    74. case 2:
    75. return '星期二'
    76. case 3:
    77. return '星期三'
    78. case 4:
    79. return '星期四'
    80. case 5:
    81. return '星期五'
    82. case 6:
    83. return '星期六'
    84. case 7:
    85. return '星期日'
    86. }
    87. }
    88. function getNum(canyuze,liexize,zhuchiren){
    89. var person= (canyuze +","+liexize+","+zhuchiren);
    90. return person.split(",").length;
    91. };
    92. module.exports = {
    93. getState: getState,
    94. getNumber: getNumber,
    95. formatDate:formatDate
    96. };

    util.js:

    1. const formatTime = date => {
    2. const year = date.getFullYear()
    3. const month = date.getMonth() + 1
    4. const day = date.getDate()
    5. const hour = date.getHours()
    6. const minute = date.getMinutes()
    7. const second = date.getSeconds()
    8. return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
    9. }
    10. const formatNumber = n => {
    11. n = n.toString()
    12. return n[1] ? n : `0${n}`
    13. }
    14. /**
    15. * 封装微信的request请求
    16. */
    17. function request(url, data = {}, method = "GET") {
    18. return new Promise(function (resolve, reject) {
    19. wx.request({
    20. url: url,
    21. data: data,
    22. method: method,
    23. header: {
    24. 'Content-Type': 'application/json',
    25. },
    26. success: function (res) {
    27. if (res.statusCode == 200) {
    28. resolve(res.data);//会把进行中改变成已成功
    29. } else {
    30. reject(res.errMsg);//会把进行中改变成已失败
    31. }
    32. },
    33. fail: function (err) {
    34. reject(err)
    35. }
    36. })
    37. });
    38. }
    39. module.exports = {
    40. formatTime,request
    41. }

    再修改首页页面中的 index.wxml  文件,在需要使用的页面进行引用即可 

    1. "/utils/comm.wxs" module="tools" />
    2. {{tools.msg}}
    3. {{tools.bar(tools.FOO)}}

    3.2 页面

    前端首页总代码 

    1. "indexbg">
    2. "true" indicator-dots="true" indicator-color="#fff" indicator-active-color="#00f">
    3. for="{{imgSrcs}}" wx:key="text">
    4. "{{item.img}}" class="swiper-item" />
    5. "/utils/comm.wxs" module="tools" />
    6. {{tools.msg}}
    7. {{tools.bar(tools.FOO)}}
    8. "mobi-title">
    9. "mobi-text">会议信息
    10. for-items="{{lists}}" wx:for-item="item" wx:key="item.id" class="bg">
    11. "list" data-id="{{item.id}}">
    12. "list-img">
    13. "video-img" mode="scaleToFill" src="{{item.image!=null?item.image:'/static/persons/2.jpg'}}">
    14. "list-detail">
    15. "list-title">{{item.title}}
    16. "list-tag">
    17. "state">{{tools.getState(item.state)}}
    18. "join">"list-num">{{tools.getNumber(item.canyuze,item.liexize,item.zhuchiren)}}人报名
    19. "list-info">{{item.location}}|{{tools.formatDate(item.starttime)}}
    20. "section">
    21. 到底啦

    效果:

  • 相关阅读:
    如何使用vsCode打开intel D435i深度相机
    Docker Desktop 设置镜像环境变量
    什么是软件工程?
    ICCV 2023 | SuS-X:仅靠类别名称微调CLIP模型,剑桥大学联合DeepMind出品
    【Vue】vuex getters 配置项
    蓝牙地址解析(NAP/UAP/LAP)
    k8s学习-CKA真题-网络策略NetworkPolicy
    【花雕动手做】有趣好玩的音乐可视化系列项目(31)--LCD1602液晶屏
    OpenCV(三十四):轮廓外接最大、最小矩形和多边形拟合
    QGIS下载各种DEM的插件(SRTM 90m/30m -ALOS 30m -Cop 30m/90m-NASADEM Global DEM)
  • 原文地址:https://blog.csdn.net/m0_73192864/article/details/133956276