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

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

)

1.搭建数据库连接,使用后端获取数据

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

javascript 复制代码
// 以下是业务服务器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', //会议信息
 };

1.请求方式的封装

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

从后台获取数据

2.化一下代码,这样写太繁琐了

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

javascript 复制代码
/**
 * 封装微信的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)
      }
    })
  });
}

然后可以改成

javascript 复制代码
loadMeetingInfos(){
    // let that=this;
    // wx.request({
    //     url: api.IndexUrl,
    //     dataType: 'json',
    //     success(res) {
    //       console.log(res)
    //       that.setData({
    //           lists:res.data.data.infoList
    //       })
    //     }
    //   })
    let that = this;
    utils.request(api.IndexUrl).then(res => {
      console.log(res);
      this.setData({
        lists: res.data.infoList
      })
    })

  },

大大的·简化了代码

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

3.前端代码

javascript 复制代码
<!--index.wxml-->
<view>
  <swiper autoplay="true" indicator-dots="true">
    <block wx:for="{{imgSrcs}}" wx:key="text">
      <swiper-item>
        <view>
          <image src="{{item.img}}" class="swiper-item" />
        </view>
      </swiper-item>
    </block>
  </swiper>
</view>
<wxs src="/utils/comm.wxs" module="tools" />

 
<view class="mobi-title">
  <text class="mobi-icon"></text>
  <text class="mobi-text">会议信息</text>
</view>
<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.image !=null? item.image : '/static/persons/2.jpg'}}"></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">
  <text>到底啦</text>
</view>
javascript 复制代码
/* pages/index/index.wxss */
.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 {
  width: 120rpx;
  height: 120rpx;
  
}

.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;
}

四、WXS的使用

用于解决一些样式问题

先再utils创建一个文件名字为comm.wxs

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

javascript 复制代码
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 '其它';
 
}

在wxs页面导出

javascript 复制代码
module.exports = {
  getState: getState,
  getNumber:getNumber,
  formatDate:formatDate,
};

在wxlm页面引入

<wxs src="/utils/comm.wxs" module="tools" />

即可使用

2. 解决统计人数问题

javascript 复制代码
var getNumber = function(canyuze,liexize,zhuchiren) {
  var person = canyuze+","+liexize+","+zhuchiren;
  return person.split(",").length;
}

3.解决时间进制问题

javascript 复制代码
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 '星期日'
  }
}
相关推荐
小吴编程之路1 小时前
MySQL 索引核心特性深度解析:从底层原理到实操应用
数据库·mysql
~莫子1 小时前
MySQL集群技术
数据库·mysql
凤山老林1 小时前
SpringBoot 使用 H2 文本数据库构建轻量级应用
java·数据库·spring boot·后端
就不掉头发1 小时前
Linux与数据库进阶
数据库
与衫1 小时前
Gudu SQL Omni 技术深度解析
数据库·sql
人生导师yxc1 小时前
微信小程序接入支付宝沙箱支付(http请求)
微信小程序·小程序
咖啡の猫2 小时前
Redis桌面客户端
数据库·redis·缓存
oradh2 小时前
Oracle 11g数据库软件和数据库静默安装
数据库·oracle
云起SAAS2 小时前
日历黄历八字排盘紫微斗数奇门遁甲姓名分析号码吉凶命理抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·日历黄历八字排盘紫微斗数
what丶k2 小时前
如何保证 Redis 与 MySQL 数据一致性?后端必备实践指南
数据库·redis·mysql