Backend data interaction and wxs application after development of WeChat applet

Table of contents

1. Backend preparation

1.1. Application configuration 

1.2. Data source configuration

2. Database

2.1. Create

2.2.Data table

2.3.Data testing 

3. Front-end

3.1. Request method integration

3.2.Data request

3.3.Usage of WXS

3.4. Style beautification

3.5. Page

        That’s it for today, I hope it can help you! ! !


1. Backend preparation

1.1. Application configuration 

Implement the imported reference and configure the reference in the project's pom.xml 

My reference configuration is as follows: 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.junlinyi</groupId>
    <artifactId>minoa</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>minoa</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <fastjson.version>1.2.70</fastjson.version>
        <jackson.version>2.9.8</jackson.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.1</version>
        </dependency>
 
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.44</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
 
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>${fastjson.version}</version>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
 
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <dependencies>
                    <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
</project>

Of course, you can add application configurations according to your own needs.

1.2. Data source configuration

Configure the database path in the back-end project

 appliation.yml

spring:
  datasource:
    #type连接池类型 DBCP,C3P0,Hikari,Druid,默认为Hikari
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_oapro?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: 123456
mybatis:
  mapper-locations: classpath*:mapper/*.xml #指定mapper文件位置
  type-aliases-package: com.junlinyi.minoa.model #指定自动生成别名所在包
 
logging:
  level:
    root: info
    com.junlinyi.minoa.mapper: debug

It is also very easy to generate mapper interfaces, model entity classes, and mapper mapping files.​ 

2. Database

2.1. Create

Create a database according to the configuration of the back-end data source.

 To create a database, you only need to fill in the input according to the following figure:

2.2.Data table

In the background, some data tables need to be prepared and certain data provided.

 The following is the data table I created, which can be created based on the reference

t_oa_data_dict

structure:

 

t_oa_data_item

structure:

t_oa_meeting_feedback

structure:

 

 

t_oa_meeting_info

structure:

 

t_oa_meeting_option

structure:

 

t_oa_meeting_room

structure:

t_oa_meeting_vote

structure:

 

t_oa_permission

structure:

 

 

t_oa_role

structure:

 

t_oa_role_permission

structure:

 

t_oa_user

structure:

 

wx_user

structure:

The design of the above data table is relatively concise and specific, without too much design.

 And you need to add some data to the above table for subsequent front-end display.

2.3.Data testing 

After completing the above, ensure that the configuration and application are completed, start the service on the backend, and enter the data request address of the backend in the browser to see if the data in the database can be queried on the backend.

The request address is entered into the service according to its own configuration. If the data can be viewed in the browser, it means that the configuration and writing of the backend and database have been completed.​ 

 as the picture shows : 

3. Front-end

In the development of WeChat mini programs, background data interaction is a very important part. Through background data interaction, data transmission and interaction between the applet and the server can be achieved.

In general, background data interaction can be achieved in the following ways:

  • Use the wx.request() method provided by WeChat to make network requests. Through this method, you can send a request to the server and get the returned data. You can use different request methods such as GET and POST to pass parameters and process the returned data.
  • Use the wx.uploadFile() method provided by WeChat to upload files. This method can upload local files to the server and obtain the data returned by the server.
  • Use WebSocket for real-time data transfer. WebSocket is a protocol for full-duplex communication over a single TCP connection, enabling real-time data transmission.

In the process of background data interaction, wxs (WeixinScript) can be used for data processing and logic control. wxs is a scripting language similar to JavaScript, which can be embedded in .wxml files and achieve dynamic effects through data binding and event binding.

The front-end applet code is improved based on the code in my blog:

WeChat applet development OA conference meeting, voting, personal center page construction and templatesicon-default.png?t=N7T8https://blog.csdn.net/m0_74915426/article/details/133959147 ?spm=1001.2014.3001.5502

3.1. Request method integration

In utils/util.js of the front-end project, encapsulate the request request method of the mini-program to reduce code duplication.

util.js

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
 
  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}
 
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
 
 
/**
 * 封装微信的request请求
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
      },
      success: function (res) {
        if (res.statusCode == 200) {
            resolve(res.data);//会把进行中改变成已成功
        } else {
          reject(res.errMsg);//会把进行中改变成已失败
        }
      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}
 
module.exports = {
  formatTime,
  request
}

3.2.Data request

Improve the homepage page in the front-end project index.js , access the data backend, and display it.

// index.js
// 获取应用实例
const app = getApp()
const api = require("../../config/app")
//应用请求的sj文件
const util = require("../../utils/util")
Page({
  //初始化数据
  data: {
    "images":[
      {
        "img": "https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner1.png",
        "text": "1"
      },
      {
        "img": "https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner2.png",
        "text": "2"
      },
      {
        "img": "https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner3.png",
        "text": "3"
      },
      {
        "img": "https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner4.png",
        "text": "4"
      },
      {
        "img": "https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner5.png",
        "text": "5"
      },
      {
        "img": "https://cdn-we-retail.ym.tencent.com/tsr/home/v2/banner6.png",
        "text": "6"
      }
    ]
  },
  // 事件处理函数
  // 获取轮播图的方法
  // loadSwiperImgs(){
  //   let that=this;
  //   wx.request({
  //       url: api.SwiperImgs,
  //       dataType: 'json',
  //       success(res) {
  //         // console.log(res)
  //         that.setData({
  //             imgSrcs:this.images
  //         })
  //       }
  //     })
  // },
//  获取首页会议信息的方法
  loadMeetingInfos(){
    let that=this;
    // wx.request({
    //     url: api.IndexUrl,
    //     dataType: 'json',
    //     success(res) {
    //       console.log(res)
    //       that.setData({
    //           lists:res.data.data.infoList
    //       })
    //     }
    //   })
      util.request(api.IndexUrl).then(res=>{
        console.log(res)
        this.setData({
          lists:res.data.infoList
        })
      }).catch(res=>{
          console.log('服器没有开启,使用模拟数据!')
      })
 
  },
  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
    // this.loadSwiperImgs();
    this.loadMeetingInfos();
  },
  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        // console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
  getUserInfo(e) {
    // 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
    // console.log(e)
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})

3.3.Usage of WXS

  • WXS code can be written in the <wxs> tag in the wxml file, or in a file with the suffix .wxs .
  • In wxs, you can use some built-in methods and objects to implement data processing, such as Math, Date, etc. At the same time, you can also use some custom functions and variables to implement specific business logic.
  • Through background data interaction and wxs application, the data display, data operation and business logic implementation of the mini program can be realized. At the same time, it can also improve the performance and user experience of mini programs.

According to the official website of WeChat Mini Program, in WeChat Developer Tools, you can create it directly by right-clicking .wxs file in which to write WXS scripts directly. 

For example, we create a .wxs file in the utils file in the project, named: tools.wxs 

function getState(state){
  // 状态:0取消会议1待审核2驳回3待开4进行中5开启投票6结束会议,默认值为1
  if(state == 0 ){
      return '取消会议';
  }else if(state == 1 ){
      return '待审核';
  }else if(state == 2 ){
      return '驳回';
  }else if(state == 3 ){
      return '待开';
  }else if(state == 4 ){
      return '进行中';
  }else if(state == 5 ){
      return '开启投票';
  }else if(state == 6 ){
      return '结束会议';
  }
      
  return '其它';
 
}
var getNumber = function(canyuze,liexize,zhuchiren) {
  var s = canyuze+','+liexize+','+zhuchiren;
  var array = s.split(',');
  var len = array.length;
  return len;
}
function formatDate(ts, option) {
  var date = getDate(ts)
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var week = date.getDay()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  
  //获取 年月日
  if (option == 'YY-MM-DD') return [year, month, day].map(formatNumber).join('-')
 
  //获取 年月
  if (option == 'YY-MM') return [year, month].map(formatNumber).join('-')
 
  //获取 年
  if (option == 'YY') return [year].map(formatNumber).toString()
 
  //获取 月
  if (option == 'MM') return  [mont].map(formatNumber).toString()
 
  //获取 日
  if (option == 'DD') return [day].map(formatNumber).toString()
 
  //获取 年月日 周一 至 周日
  if (option == 'YY-MM-DD Week')  return [year, month, day].map(formatNumber).join('-') + ' ' + getWeek(week)
 
  //获取 月日 周一 至 周日
  if (option == 'MM-DD Week')  return [month, day].map(formatNumber).join('-') + ' ' + getWeek(week)
 
  //获取 周一 至 周日
  if (option == 'Week')  return getWeek(week)
 
  //获取 时分秒
  if (option == 'hh-mm-ss') return [hour, minute, second].map(formatNumber).join(':')
 
  //获取 时分
  if (option == 'hh-mm') return [hour, minute].map(formatNumber).join(':')
 
  //获取 分秒
  if (option == 'mm-dd') return [minute, second].map(formatNumber).join(':')
 
  //获取 时
  if (option == 'hh')  return [hour].map(formatNumber).toString()
 
  //获取 分
  if (option == 'mm')  return [minute].map(formatNumber).toString()
 
  //获取 秒
  if (option == 'ss') return [second].map(formatNumber).toString()
 
  //默认 时分秒 年月日
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
 
function getWeek(n) {
  switch(n) {
      case 1:
      return '星期一'
      case 2:
      return '星期二'
      case 3:
      return '星期三'
      case 4:
      return '星期四'
      case 5:
      return '星期五'
      case 6:
      return '星期六'
      case 7:
      return '星期日'
  }
}
module.exports = {
  getState: getState,
  getNumber: getNumber,
  formatDate:formatDate
};

 This document is a perfect and more beautifying display of the number of people and time in the meeting information.

3.4. Style beautification

Further effect beautification in index.wxss.

 

/**index.wxss**/
.swiper-item {
  height: 300rpx;
  width: 100%;
  border-radius: 10rpx;
}
.mobi-title {
  font-size: 12pt;
  color: #777;
  line-height: 110%;
  font-weight: bold;
  width: 100%;
  padding: 15rpx;
  background-color: #f3f3f3;
}
 
.mobi-icon {
  padding: 0rpx 3rpx;
  border-radius: 3rpx;
  background-color: #ff7777;
  position: relative;
  margin-right: 10rpx;
}
 
/*list*/
.list {
  display: flex;
  flex-direction: row;
  width: 100%;
  padding: 0 20rpx 0 0;
  border-top: 1px solid #eeeeee;
  background-color: #fff;
  margin-bottom: 5rpx;
  /* border-radius: 20rpx;
  box-shadow: 0px 0px 10px 6px rgba(0,0,0,0.1); */
}
 
.list-img {
  display: flex;
  margin: 10rpx 10rpx;
  width: 150rpx;
  height: 220rpx;
  justify-content: center;
  align-items: center;
}
 
.list-img .video-img {
  border-radius: 4px;
  width: 130rpx;
  height: 140rpx; 
}
 
.list-detail {
  margin: 10rpx 10rpx;
  display: flex;
  flex-direction: column;
  width: 600rpx;
  height: 220rpx;
}
 
.list-title text {
  font-size: 11pt;
  color: #333;
  font-weight: bold;
}
 
.list-detail .list-tag {
  display: flex;
  height: 70rpx;
}
 
.list-tag .state {
  font-size: 9pt;
  color: #81aaf7;
  width: 120rpx;
  border: 1px solid #93b9ff;
  border-radius: 2px;
  margin: 10rpx 0rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
 
.list-tag .join {
  font-size: 11pt;
  color: #bbb;
  margin-left: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
 
.list-tag .list-num {
  font-size: 11pt;
  color: #ff6666;
}
 
.list-info {
  font-size: 9pt;
  color: #bbb;
  margin-top: 20rpx;
}
.bottom-line{
  display: flex;
  height: 60rpx;
  justify-content: center;
  align-items: center;
  background-color: #f3f3f3;
}
.bottom-line text{
  font-size: 9pt;
  color: #666;
}

3.5. Page

Modify the  index.wxml on the homepage  file

<!--index.wxml-->
<view>
    <swiper autoplay="true" indicator-dots="true" indicator-color="#fff" indicator-active-color="#00f">
        <block wx:for="{
   
   {images}}" wx:key="text">
            <swiper-item>
                <view>
                    <image src="{
   
   {item.img}}" class="swiper-item" />
                </view>
            </swiper-item>
        </block>
    </swiper>
</view>
<view class="mobi-title">
    <text class="mobi-icon"></text>
    <text>会议信息</text>
</view>
<wxs src="../../utils/tools.wxs" module="tools" />
<block wx:for-items="{
   
   {lists}}" wx:for-item="item" wx:key="item.id">
    <view class="list" data-id="{
   
   {item.id}}">
        <view class="list-img">
            <image class="video-img" mode="scaleToFill" src="{
   
   {item.remark}}"></image>
        </view>
        <view class="list-detail">
            <view class="list-title"><text>{
   
   {item.title}}</text></view>
            <view class="list-tag">
                <view class="state">{
   
   {tools.getState(item.state)}}</view>
                <view class="join"><text class="list-num">{
   
   {tools.getNumber(item.canyuze,item.liexize,item.zhuchiren)}} </text>人报名</view>
            </view>
            <view class="list-info"><text>{
   
   {item.location}}</text> | <text>{
   
   {tools.formatDate(item.starttime)}}</text></view>
        </view>
    </view>
</block>
<view class="section bottom-line">
		<text>到底啦</text>
</view>
 

After the background service is started, the effect can be seen in the simulator: 

                                        

        That’s it for today, I hope it can help you! ! !

Guess you like

Origin blog.csdn.net/m0_74915426/article/details/133978700