您好,小程序模板欢迎您。
小程序模板
当前位置 : 首页> 小程序教程> 微信小程序连接数据库与WXS的使用

微信小程序连接数据库与WXS的使用

前言

      很多同志们再写小程序的过程中,不知道该怎么发起HTTP请求到后端,在Web环境中发起HTTPS请求是很常见的,但是微信小程序是腾讯内部的产品,不能直接打开一个外部的链接。例如,在微信小程序中不能直接打开www.taobao.com网站,但是,在小程序开发的时候,如果需要请求一个网站的内容或者服务,如何实现?虽然微信小程序里面不能直接访问外部链接,但是腾讯为开发者封装好了一个wx.request(object)的API。

一、搭建数据库连接

1.接口地址URL

其他的东西还是基本与我们发送ajax请求一致的。

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

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

先定义本机开发的API地址,具体的请求在下面定义方便管理。

2.请求方式的封装

 loadMeetingInfos(){
    let that=this;
    wx.request({
        url: api.IndexUrl,
        dataType: "json",
        success(res) {
          console.log(res)
          that.setData({
              lists:res.data.data.infoList
          })
        }
      })
  }

以上是我们发送请求的代码,虽然比较简短但还是要在需要的地方进行编写,简单的代码反复性高那我们就可以对它进行封装。

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

/**
 * 封装微信的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中导出和需要使用的页面js中使用实const util = require("../../utils/util")

 //首页会议信息的ajax
  loadMeetingInfos() {
    let that = this;
    util.request(api.IndexUrl).then(res => {
      this.setData({
        lists: res.data.infoList
      })
    })
  }

是不是看起来又少了很多代码

3.后端代码

后端SpringBoot搭建的,引入了mysql、mybatisplus、swagger、lombok等依赖。

数据库表结构:

部分代码:

@RestController
@RequestMapping("/wx/home")
public class WxHomeController {
    @Autowired
    private InfoMapper infoMapper;
    @RequestMapping("/index")
    public Object index(Info info) {
        List infoList = infoMapper.list(info);
        Map data = new HashMap();
        data.put("infoList",infoList);
        return ResponseUtil.ok(data);
    }
}

这里我相信大家都懂不必多说!!!!!

 4.前端代码

wxml




  
    
      
        
          < image src="{{item.img}}" class="swiper-item" />
        
      
    
  




  
  会议信息


  
    
      < image class="video-img" mode="scaleToFill" src="{{item.image !=null? item.image : "/static/persons/6.png"}}">
    
    
      {{item.title}}
      
        {{item.state}}
        {{item.num}}人报名
      
      {{item.location}}|{{item.starttime}}
    
  


  到底啦

wxss

/**index.wxss**/
.section{
  color: #aaa;
  display: flex;
  justify-content: center;
}

.list-info {
  color: #aaa;
}

.list-num {
  color: #e40909;
  font-weight: 700;
}

.join {
  padding: 0px 0px 0px 10px;
  color: #aaa;
}

.state {
  margin: 0px 6px 0px 6px;
  border: 1px solid #93b9ff;
  color: #93b9ff;
}

.list-tag {
  padding: 3px 0px 10px 0px;
  display: flex;
  align-items: center;
}

.list-title {
  display: flex;
  justify-content: space-between;
  font-size: 11pt;
  color: #333;
  font-weight: bold;


}

.list-detail {
  display: flex;
  flex-direction: column;
  margin: 0px 0px 0px 15px;
}

.video-img {
  width: 80px;
  height: 80px;
}

.list {
  display: flex;
  flex-direction: row;
  border-bottom: 1px solid #6b6e74;
  padding: 10px;
}

.mobi-text {
  font-weight: 700;
  padding: 15px;
}

.mobi-icon {
  border-left: 5px solid #e40909;
}

.mobi-title {
  background-color: rgba(158, 158, 142, 0.678);
  margin: 10px 0px 10px 0px;
}

.swiper-item {
  height: 300rpx;
  width: 100%;
  border-radius: 10rpx;
}

.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #aaa;
}

.userinfo-avatar {
  overflow: hidden;
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.usermotto {
  margin-top: 200px;
}

效果展示:

 其实我们这个页面还存在着一些的问题,比如说这个会议的状态不应该显示数字,而是数字对应的状态是什么?参会的人数有多少?会议的时间显示等问题...下面就用wxs带大家解决该问题。

二、WXS的使用

WXS(WeChat Mini Program Storage)是微信小程序提供的本地存储方案,用于在小程序中进行数据的存储和管理。相比远程数据库,WXS更适合于小规模、简单的数据存储需求。

1.wxs 文件

在微信开发者工具里面,右键可以直接创建 .wxs 文件,在其中直接编写 WXS 脚本。

// /pages/comm.wxs

var foo = ""hello world" from comm.wxs";
var bar = function(d) {
  return d;
}
module.exports = {
  foo: foo,
  bar: bar
};
  • exports: 通过该属性,可以对外共享本模块的私有变量与函数。

在需要使用的页面进行引用即可


 {{tools.msg}} 
 {{tools.bar(tools.FOO)}} 

页面输出:

some msg
"hello world" from tools.wxs

学会了基本的wxs的使用,我们在刚刚的页面中进行操作一手。

2.解决数据显示数字问题

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 "其它";

}

 3.解决统计人数问题

function formatNumber(liexize,canyuze,zhuchiren) {
    var person = liexize+","+canyuze+","+zhuchiren;
    return person.split(",").length;
}

4.解决时间进制问题

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(":")
}

 效果展示

 请添加图片描述

到这里我的分享就结束了,欢迎到评论区探讨交流!!

联系客服 意见反馈

签到成功!

已连续签到1天,签到3天将获得积分VIP1天

知道了