[物联网设计竞赛国一]技术分享之微信小程序(2)

接下来我将详细的讲解这些功能实现的原理及分享代码

1.地理位置的获取

微信小程序自带获取地址的组件,我们直接调用map组件即可。

js部分的代码

Page({
  data: {
    latitude: 23.099994,
    longitude: 113.324520,
    markers: [{
      id: 1,
      latitude: 23.099994,
      longitude: 113.324520,
      name: 'T.I.T 创意园'
    }],
    covers: [{
      latitude: 23.099994,
      longitude: 113.344520,
      iconPath: '/image/location.png'
    }, {
      latitude: 23.099994,
      longitude: 113.304520,
      iconPath: '/image/location.png'
    }]
  },
  onReady: function (e) {
    this.mapCtx = wx.createMapContext('myMap')
  },
  getCenterLocation: function () {
    this.mapCtx.getCenterLocation({
      success: function(res){
        console.log(res.longitude)
        console.log(res.latitude)
      }
    })
  },
  moveToLocation: function () {
    this.mapCtx.moveToLocation()
  },
  translateMarker: function() {
    this.mapCtx.translateMarker({
      markerId: 1,
      autoRotate: true,
      duration: 1000,
      destination: {
        latitude:23.10229,
        longitude:113.3345211,
      },
      animationEnd() {
        console.log('animation end')
      }
    })
  },
  includePoints(){
    wx.switchTab({
      url: '/pages/home',
    })
    
  },
})

wxml部分代码

<view class="page-body">
  <view class="page-section page-section-gap">
    <map
      id="myMap"
      style="width: 100%; height: 300px;"
      latitude="{{latitude}}"
      longitude="{{longitude}}"
      markers="{{markers}}"
      covers="{{covers}}"
      show-location
    ></map>
  </view>
  <view class="btn-area">
    
    <button bindtap="moveToLocation" class="page-body-button" type="primary" style="position: relative; left: 1rpx; top: 55rpx">获取位置</button>
    
    <button bindtap="includePoints" class="page-body-button" type="primary" style="position: relative; left: 1rpx; top: 110rpx">进入电梯系统</button>
  </view>
</view>

wxss样式代码

.page-section-gap{
  box-sizing: border-box;
  padding: 0 30rpx;
}

.page-body-button {
  margin-bottom: 30rpx;
}

 json代码

{
  "usingComponents": {}
}

app.json的配置

{
  "pages": [
    "pages/denglu",
    "pages/index",
    "pages/login",
    "pages/home",
    "pages/huawei_loT",
    "pages/shangbao",
    "pages/geren",
    "pages/kk",
    "pages/cloudfunctions"
    
    
  ],
  "window": {
    "navigationBarTitleText": "电梯管理系统",
    "navigationBarTextStyle": "black",
    "navigationBarBackgroundColor": "#44ADFB"
  },
  "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
  },
  "tabBar": {
    "list": [
      {
        "pagePath": "pages/home",
        "text": "首页",
        "iconPath": "pages/images/1.png",
        "selectedIconPath": "pages/images/2.jpg"
      },
      {
        "pagePath": "pages/huawei_loT",
        "text": "信息页",
        "iconPath": "pages/images/3.png",
        "selectedIconPath": "pages/images/4.jpg"
      },
      {
        "pagePath": "pages/login",
        "text": "个人页",
        "iconPath": "pages/images/1.png",
        "selectedIconPath": "pages/images/2.jpg"
      }
    ]
  },
  "networkTimeout": {
    "request": 10000,
    "downloadFile": 10000
  },
  "debug": true,
  "style": "v2",
  "componentFramework": "glass-easel",
  "sitemapLocation": "sitemap.json",
  "lazyCodeLoading": "requiredComponents"
}

不配置app.json会报错,亲身尝试 

 

2.从云平台获取数据并将其显示在页面上

这部分有点难度,首先要在云平台上把自己的模型部署好,能从设备端采集数据并上报属性,有很多的传输方式,常见的是esp的wifi模块,4g模块,5g模块,NB-lot传输,实践下来发现还是wifi模块更简单一点。我们组参加的是广和通赛道,必须要用广和通4g模块l610,难度主要在上报属性那块,那个AT指令上报的时候要固定上报的字符串长度,但数据是随时变化的,当时也困住了我们几天,最后使用strlen函数,每次上报之前都要用函数数一下字符串再进行上报。

接下来是代码分享。

wxml代码

<swiper indicator-dots circular     indicator-active-color="white">
   <swiper-item >
     <image src="./images/999.png" style="width: 750rpx; height: 231rpx; display: inline-block; box-sizing: content-box"></image>
   </swiper-item> 
   
   <swiper-item>
   <image src="./images/12.png"></image>
 </swiper-item>
 </swiper>
 <text class="userinfo">提示信息:</text>
 
 
<button type="primary"bindtap="touchBtn_gettoken" style="position: relative; left: 2rpx; top: -41rpx; width: 354rpx; height: 77rpx; display: block; box-sizing: border-box">更新token</button>
<button type="default"bindtap="touchBtn_getshadow" style="position: relative; left: -1rpx; top: -41rpx; width: 354rpx; height: 77rpx; display: block; box-sizing: border-box">获取云端数据</button>
<button type="default"bindtap="touchBtn_getCommand" style="position: relative; left: -1rpx; top: -41rpx; width: 354rpx; height: 77rpx; display: block; box-sizing: border-box">警示灯开</button>
<button type="default"bindtap="touchBtn_getCommandd" style="position: relative; left: -1rpx; top: -41rpx; width: 354rpx; height: 77rpx; display: block; box-sizing: border-box">警示灯关</button>


<button  class="bt_2"style="position: relative; left: -196rpx; top: 29rpx; width: 248rpx; height: 154rpx; display: block; box-sizing: border-box">{{result5}}</button>
<button class="bt_2"style="position: relative; left: 158rpx; top: -127rpx; width: 248rpx; height: 156rpx; display: block; box-sizing: border-box">{{result1}}</button>
<button class="bt_2"style="width: 248rpx; height: 156rpx; display: block; box-sizing: border-box; left: -196rpx; top: -86rpx; position: relative">{{result4}}</button>
<button class="bt_2"style="position: relative; left: 158rpx; top: -244rpx; width: 248rpx; height: 156rpx; display: block; box-sizing: border-box">{{result3}}</button>
<button class="bt_6"style="position: relative; left: -12rpx; top: -180rpx" style="position: relative; left: -20rpx; top: -202rpx">{{result2}}</button>

















 js部分代码

Page({

  /**
   * 页面的初始数据
   */
  data: {
    result:'等待获取token',

  },

  /**
   * 生命周期函数--监听页面加载
   */
  touchBtn_gettoken:function() {
    console.log("获取token按钮按下");
    this.setData({result:'获取token按钮按下'})
    this.gettoken();

  },
  touchBtn_getshadow:function() {
    console.log("获取影子按钮按下");
    this.setData({result:'获取影子设备按钮按下'});
    this.getshadow();
  },
  touchBtn_getCommand:function() {
    console.log("设备命令下发按钮按下");
    this.setData({result:'设备命令下方按钮按下,正在下发'});
    this.setCommand();


  },
  touchBtn_getCommandd:function() {
    console.log("设备命令下发按钮按下");
    this.setData({result:'设备命令下方按钮按下,正在下发'});
    this.setCommandd();


  },
  /**
     * 获取token
     */
    gettoken:function(){
      console.log("开始获取。。。");//打印完整消息
      var that=this;  //这个很重要,在下面的回调函数中由于异步问题不能有效修改变量,需要用that获取
      wx.request({
          url: 'https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens',
          data:'{"auth": { "identity": {"methods": ["password"],"password": {"user": {"name": "yonghu1","password": "","domain": {"name": "hid_72qsqum1w6h3phr"}}}},"scope": {"project": {"name": "cn-north-4"}}}}',
          method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
          header: {'content-type': 'application/json' }, // 请求的 header 
          success: function(res){// success
            // success
              console.log("获取token成功");//打印完整消息
              console.log(res);//打印完整消息
              var token='';
              token=JSON.stringify(res.header['X-Subject-Token']);//解析消息头token
              token=token.replaceAll("\"", "");
              console.log("获取token=\n"+token);//打印token
              wx.setStorageSync('token',token);//把token写到缓存中,以便可以随时随地调用
          },
          fail:function(){
              // fail
              console.log("获取token失败");//打印完整消息
          },
          complete: function() {
              // complete
              console.log("获取token完成");//打印完整消息
          } 
      });
  },
  getshadow:function(){
    console.log("开始获取影子");//打印完整消息
    var that=this;  //这个很重要,在下面的回调函数中由于异步问题不能有效修改变量,需要用that获取
    var token=wx.getStorageSync('token');//读缓存中保存的token
    console.log("我的toekn:"+token);//打印完整消息
    wx.request({
        url: 'https://iotda.cn-north-4.myhuaweicloud.com/v5/iot/d27ce9bec3c3430f9cc1fb5af9b12680/devices/66823ab72ca97925e0670ee9_zhineneng001/shadow',
        data:'',
        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {'content-type': 'application/json','X-Auth-Token':token }, //请求的header 
        success: function(res){// success
          // success
            console.log(res);//打印完整消息
            var shadow=JSON.stringify(res.data.shadow[1].reported.properties);
            console.log('设备影子数据:'+shadow);
            var weight=JSON.stringify(res.data.shadow[1].reported.properties.weight);
            var wind=JSON.stringify(res.data.shadow[1].reported.properties.wind);
            var Accel_z=JSON.stringify(res.data.shadow[1].reported.properties.Accel_z);
            var Angle_x=JSON.stringify(res.data.shadow[1].reported.properties.Angle_x);
            var Angle_y=JSON.stringify(res.data.shadow[1].reported.properties.Angle_y);
            console.log('重量='+weight+'kg');
            console.log('风速='+wind);
            console.log('加速度z='+Accel_z+'m/s*s');
            console.log('加速度x='+Angle_x+'m/s*s');
            console.log('加速度y='+Angle_y+'m/s*s');
            that.setData({result5:'重量:'+weight+'kg'});
            that.setData({result1:'风速:'+wind+'m/s'});
            that.setData({result2:'加速度z:'+Accel_z+'m/s*s'});
            that.setData({result3:'倾角x:'+Angle_x+'c'});
            that.setData({result4:'倾角y:'+Angle_y+'c'});
        },
        fail:function(){
            // fail
            console.log("获取影子失败");//打印完整消息
        },
        complete: function() {
            // complete
            console.log("获取影子完成");//打印完整消息
        } 
    });


},
/**
     * 设备命令下发
     */
    setCommand:function(){
      console.log("开始下发命令。。。");//打印完整消息
      var that=this;  //这个很重要,在下面的回调函数中由于异步问题不能有效修改变量,需要用that获取
      var token=wx.getStorageSync('token');//读缓存中保存的token
      wx.request({
          url: 'https://iotda.cn-north-4.myhuaweicloud.com/v5/iot/d27ce9bec3c3430f9cc1fb5af9b12680/devices/66823ab72ca97925e0670ee9_zhineneng001/commands',
          data:'{"service_id": "Sprayswitchcontrol","command_name": "SpraySwitchCommand","paras": { "SpraySwitchParam":1}}',
          method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
          header: {'content-type': 'application/json','X-Auth-Token':token }, //请求的header 
          success: function(res){// success
              // success
              console.log("下发命令成功");//打印完整消息
              console.log(res);//打印完整消息
              
              
          },
          fail:function(){
              // fail
              console.log("命令下发失败");//打印完整消息
              console.log("请先获取token");//打印完整消息
          },
          complete: function() {
              // complete
              console.log("命令下发完成");//打印完整消息
              that.setData({result:'设备命令下发完成'});
          } 
      });
  },
  setCommandd:function(){
    console.log("开始下发命令。。。");//打印完整消息
    var that=this;  //这个很重要,在下面的回调函数中由于异步问题不能有效修改变量,需要用that获取
    var token=wx.getStorageSync('token');//读缓存中保存的token
    wx.request({
        url: 'https://iotda.cn-north-4.myhuaweicloud.com/v5/iot/d27ce9bec3c3430f9cc1fb5af9b12680/devices/66823ab72ca97925e0670ee9_zhineneng001/commands',
        data:'{"service_id": "Sprayswitchcontrol","command_name": "SpraySwitchCommand","paras": { "SpraySwitchParam":0}}',
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {'content-type': 'application/json','X-Auth-Token':token }, //请求的header 
        success: function(res){// success
            // success
            console.log("下发命令成功");//打印完整消息
            console.log(res);//打印完整消息
            
            
        },
        fail:function(){
            // fail
            console.log("命令下发失败");//打印完整消息
            console.log("请先获取token");//打印完整消息
        },
        complete: function() {
            // complete
            console.log("命令下发完成");//打印完整消息
            that.setData({result:'设备命令下发完成'});
        } 
    });
},












  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})

里面的密码我删除了,这里是从云平台获取影子数据,还有在微信小程序端控制灯的开关,在stm32里面的程序我就不展示了,就是解析串口的数据,然后通过stm32控制引脚电平。获取云平台数据的信息都是个人化的,你们如果想自己开发可以借鉴下面这位博主

https://blog.csdn.net/weixin_43351158/article/details/131284763

wxss代码

/* pages/huawei_loT.wxss */
swiper {
  height: 300rpx;
}
swiper image {
  height: 100%;
  width: 100%;
}
.view_class {
display:flex;
flex-direction: row;
justify-content: center;
resize:horizontal;
overflow: hidden;
margin: 1em;

}
.item{
  margin: 20px 8px auto 1px;
  padding: 0.3em;
  width:65px;
  min-width: 0;
  background-color: #1B5385;
  color: white;
  font-family: monospace;
  font-size: 12px;
}
.bt_1{
  margin-top: 40rpx;
  background: linear-gradient(#ccfbff, #ef96c5); 
}
.bt_2{
  margin-top: 40rpx;
  background: linear-gradient(to right, #ead6ee, #a0f1ea); 
}/* 对角渐变 */
.bt_3{
  margin-top: 40rpx;
  background: linear-gradient(to bottom right, #eebd89, #d13abd);
}/* 半透明渐变 */
.bt_4{
  margin-top: 40rpx;
  background: linear-gradient(rgb(252, 126, 67), rgba(255,0,0,0)); 
  width: 80%;  
  border-radius: 50rpx;
  /* background: bg_red; */
}/* 多色渐变 */
.bt_6{
  margin-top: 40rpx;
  background: linear-gradient(to right,#f9957f, #f2f5d0, #aebaf8, #c973ff );
  width: 80%;  
  border-radius: 50rpx;
  
}

里面是几种渐变的格式,可以选择自己喜欢的渐变,美化自己的页面。

json代码 

{
  "usingComponents": {}
}

3.人员登录

这其实也是比较常见的功能之一,就是输入账号和密码,实现登录。比较常规的方法是从mysql数据库中获取人员姓名和密码,但由于这个微信小程序只要一个人员身份信息,我就直接在js代码里面定义了人员身份和密码。

下面是代码分享。

wxml代码

<!--pages/login.wxml-->
<view class="welcome">
<p>欢迎使用智能电梯系统</p >
</view>

<view class='login_block'  style="position: absolute; left: -4rpx; top: 262rpx; width: 704rpx; height: 681rpx; display: flex; box-sizing: border-box">
  <view><span class="iconfont icon-geren"></span><input type='text' placeholder="请输入账号" bindinput='inputUsr' class='input'></input></view>
  <view><span class="iconfont icon-mima1"></span><input password='true' placeholder="请输入密码" bindinput='inputPwd'class='input'></input></view>
  <button type='primary' bindtap='confirmPwd' class="confirm">确定</button>

</view>
<image style="position: relative; left: 68rpx; top: 24rpx; width: 612rpx; height: 264rpx; display: inline-block; box-sizing: border-box" src="/pages/images/999.png"/>

js代码

// pages/login/index.js
Page({

  /**ss
   * 页面的初始数据g
   */
  data: {
      password_input:"",
      usr:"小张",
      key:"12345",
  },
    inputUsr:function(e){
  this.setData({
      user_input: e.detail.value
    })
},
inputPwd:function(e){
  this.setData({
    password_input: e.detail.value
  })
},

confirmPwd:function(){
  var usr = this.data.user_input;
  var pwd = this.data.password_input;
  var that = this
  if(pwd==""||usr==""){
      wx.showToast({
        title: '请输入账号和密码',
        icon: 'none',
        duration: 2000
      })
  }
  else if(pwd != this.data.key||usr != this.data.usr){
    wx.showToast({
      title: '账号或密码错误',
      icon: 'none',
      duration: 2000
    })
  }else{
    wx.showToast({
      title: '验证通过',
      icon: 'success',
      duration: 1000
    })
    
    wx.setStorage({
      key: "password",
      data: pwd,
    })
    wx.navigateTo({
      url: '/pages/geren',
    })
    
  }
}



})

可以修改里面的 usr和key,个性化定义身份和密码。

wxss代码

/* pages/login/index.wxss */
page{
  background-color: rgb(97, 145, 248);
}

.login_block{
  position: absolute;
  left: 0;right: 0;top: 0;bottom: 0;
  display:flex;
  justify-content: center;
  flex-direction: column;

  width: 86vw;
  height: 50vh;
  background-color: white;
  margin: auto;
  padding: 3vh 3vh;
  border: 1px solid rgb(202, 201, 201);
  border-radius: 20px;
}

.login_block .input{
    border:none;
    border-bottom: 1px solid #000000;
    margin: 2vh 2vh;
}
.login_block .confirm{
    height: 8vh;
    width:40vw;
    line-height: 8vh;
    margin-top: 4vh;
    background-color: rgb(123, 177, 177);

}
.welcome{
    display: flex;
    color: azure;
    justify-content: center;
    margin-top: 5vh;
}

 json代码

{
  "usingComponents": {}
}

4.上报信息到数据库

首先你要拥有一个自己的云数据库,然后连接云数据库,将数据存入数据库中。

下面是代码分享

wxml代码

<form bindsubmit="btnSubmit">
 
  上报日期:<input style="width: 750rpx; height: 80rpx; display: block; box-sizing: border-box" name="time" placeholder="请输入日期"/>
  电梯老旧情况:<input style="width: 750rpx; height: 80rpx; display: block; box-sizing: border-box" name="name" placeholder="请输入详情"/>
  钢丝绳是否正常:<input style="width: 750rpx; height: 80rpx; display: block; box-sizing: border-box" name="sex" placeholder="请输入详情"/>
  检修次数:<input style="width: 750rpx; height: 80rpx; display: block; box-sizing: border-box" name="age" placeholder="请输入次数"/>
  标准节处的螺栓螺母是否正常:<input style="width: 750rpx; height: 80rpx; display: block; box-sizing: border-box" name="kongfu" placeholder="请输入详情"/>
  <button class=".btn-grad1" form-type="submit" style="position: relative; left: -196rpx; top: 145rpx">添加</button>
  <button class=".btn-grad1" form-type="reset" style="position: relative; left: 185rpx; top: 23rpx">重置</button>
  <button class=".btn-grad222" bindtap="uploadPhoto"  style="position: relative; left: -29rpx; top: -235rpx">上传图片</button>
  
  
  
</form>
<form bindsubmit="btnDelete">
ID:<input style="width: 750rpx; height: 80rpx; display: block; box-sizing: border-box" name="id" placeholder="请输入要删除的ID"/>
  <button class=".btn-grad1" form-type="submit" style="position: relative; left: -199rpx; top: 58rpx">删除</button>
  <button class=".btn-grad1" form-type="reset" style="position: relative; left: 194rpx; top: -66rpx">重置</button>
</form>
<button class=".btn-grad333"bindtap="getceshi"   style="position: relative; left: -4rpx; top: -57rpx; width: 421rpx; height: 108rpx; display: block; box-sizing: border-box">查看以往数据</button>

 这里面功能比较多,有增删数据还有查看数据库的数据的跳转按钮,跳转按钮不了解的,我后期可能会出一个跳转的详细讲解,现在只要建立查看数据页面的时候把它命名为kk就行了

js代码

Page({


  /**
   * 页面的初始数据
   */
  data: {
    list:{},
    

     
  },
  uploadPhoto: function(){
   wx.chooseMedia({
    count: 1,
    mediaType: ['image','video'],
    sourceType: ['album', 'camera'],
    maxDuration: 30,
    camera: 'back',
    success(res) {
      console.log(res.tempFiles[0].tempFilePath)
      console.log(res.tempFiles[0].size)
      
      
      
    }
  })
},
  getceshi()
  {
    wx.navigateTo({
      url:'/pages/kk',
    })
  },
  btnSubmit(res) {
    
    var time =res.detail.value.time
    var name = res.detail.value.name
    var sex = res.detail.value.sex
    var age = res.detail.value.age
    var kongfu = res.detail.value.kongfu
    
  const db=wx.cloud.database({env:"yunduan-3govl6jabeb20270"})
   db.collection("diantiqingkang").add({
      data: {
        riqi:time,
        wanqu: name,
        laojiu: sex,
        cishu: Number(age),
        biaozhunjie: kongfu,
        
      }
    })
    .then(res => {
      wx.showToast({
        title: '添加成功!',
      })
    })
  },
  btnDelete(res) {
    var id = res.detail.value.id
    const db=wx.cloud.database({env:"yunduan-3govl6jabeb20270"})
    db.collection("33").doc(id).remove()
    .then(res => {
      console.log(res)
      wx.showToast({
        title: '删除成功!',
      })
    })
  }
  /**
   * 生命周期函数--监听页面加载
   */
  
})

env后面是自己的环境,你开通后都会在右上角显示 

wxss代码

/* pages/cloudfunctions.wxss */
/* pages/denglu.wxss */
.btn-grad1 {
  background-image: linear-gradient(to right, #77A1D3 0%, #79CBCA  51%, #77A1D3  100%);
  margin: 10px;
  padding: 15px 45px;
  text-align: center;
  text-transform: uppercase;
  transition: 0.5s;
  background-size: 200% auto;
  color: white;            
  box-shadow: 0 0 20px rgb(224, 224, 223);
  border-radius: 10px;
  display: block;
  }
  
  .btn-grad1:hover {
  background-position: right center; /* change the direction of the change here */
  color: #fff;
  text-decoration: none;
  }

  .btn-labeltop{

  background-color: #79CBCA;
  height: 10px;
  width: 100%;

  }

  .btn-grad222 {
    background-color: rgb(218, 191, 42);
    margin: 10px;
    padding: 15px 45px;
    text-align: center;
    text-transform: uppercase;
    transition: 0.5s;
    background-size: 200% auto;
    color: rgb(8, 8, 8);            
    border-radius: 10px;
    display: block;
    }
    .btn-grad333 {
      background-color: rgba(217, 192, 238, 0.932);
      margin: 10px;
      padding: 15px 45px;
      text-align: center;
      text-transform: uppercase;
      transition: 0.5s;
      background-size: 200% auto;
      color: rgb(8, 8, 8);            
      border-radius: 10px;
      display: block;
      }

 json代码

{
  "usingComponents": {}
}

app.json代码

App({
  onLaunch: function () {
    wx.cloud.init({
      // env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
      env: 'yunduan-3govl6jabeb20270',
      // 是否在将用户访问记录到用户管理中,在控制台中可见,默认为false
      traceUser: false,
    });
  },
});
wx.cloud.callFunction({
  name: 'cloudbase_module',
  data: {
    name: 'wx_user_get_open_id',
  },
  success: (res) => {
    const openId = res.result?.openId;
    console.log('获取到的openId:', openId);
  },
});

使用云数据库要在app.json里面初始化云数据库环境,别忘了,不然使用不了云数据库。 

 

在手机页查看数据

这里的前提是数据库里面要有数据,把数据库里面的数据解析然后显示在页面上,切记数据库里面变量别用中文,超级坑。

wxml代码

<!--pages/kk.wxml-->
<view class="table">
<view class="tr bg-w">
<view class="th" style="width: 179rpx; height: 89rpx; display: flex; box-sizing: border-box">日期</view>
<view class="th" style="width: 202rpx; height: 89rpx; display: flex; box-sizing: border-box">电梯老旧情况</view>
<view class="th" style="width: 210rpx; height: 89rpx; display: flex; box-sizing: border-box; left: 0rpx; top: 0rpx">螺栓螺母</view>
<view class="th" style="width: 200rpx; height: 89rpx; display: flex; box-sizing: border-box">标准节是否正常</view>
<view class="th" style="width: 124rpx; height: 89rpx; display: flex; box-sizing: border-box">图片</view>
</view>
<block wx:for="{{list}}" wx:key="{[code]}" >
<view class="tr" wx:if="{{index % 2 == 0}}" style="width: 750rpx; height: 93rpx; display: flex; box-sizing: border-box">
  <view class="td">{{item.riqi}}</view>
  <view class="td">{{item.laojiu}}</view>
  <view class="td">{{item.wanqu}}</view>
  <view class="td">{{item.biaozhunjie}}</view>
  <view class="td">{{item.tupian}}</view>
  
  
  </view>
<view class="tr"wx:else style="width: 750rpx; height: 93rpx; display: flex; box-sizing: content-box">
  <view class="td">{{item.riqi}}</view>
  <view class="td">{{item.laojiu}}</view>
  <view class="td">{{item.wanqu}}</view>
  <view class="td">{{item.biaozhunjie}}</view>
  <view class="td">{{item.tupian}}</view>
 

</view>
</block>
</view>

我在数据库定义的变量名是riqi,laojiu,wanqu,biaozhunjie,tupian,别用中文,不然你解析数据的时候解析不出来,很麻烦。 

js代码

Page({
  data:{
      list:[ ]
  },
  onLoad(){
wx.cloud.database().collection('diantiqingkang').get()
.then(res =>{
  console.log('第二种方法请求成功',res.data)
  this.setData({
      list:res.data
  })
  })
.catch(err =>{
  console.log('第二种方法请求失败',err)    
})
},
//选择图片
choseImg(){
  var that = this
  //上传图片第一步
  wx.chooseImage({
    count: 1,  //可以选择多少张图片
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'], //设置图片来源
    success (res) {
      const tempFilePaths = res.tempFilePaths
      that.uploadImg(tempFilePaths[0])   //要上传图片的临时地址
    }
  })
},
    //上传文件
uploadImg(temFile){
  console.log(temFile)
  wx.cloud.uploadFile({
    cloudPath:'test.jpg', 
    filePath: temFile,
    success (res){
      const data = res.data
      console.log("上传成功")
      //do something
    },fail(res){
      console.log("上传失败")
    }
  })
},
//图片点击事件
imgYu:function(event){
  var src = event.currentTarget.dataset.src;//获取data-src
  //var imgList = event.currentTarget.dataset.list;//获取data-list
 var imgList = this.data.images
  //图片预览
  wx.previewImage({
  current: src, // 当前显示图片的http链接
  urls: imgList // 需要预览的图片http链接列表
  })
  },
})

 wxss代码

/* pages/kk.wxss */
/* pages/table/table.wxss */
.table {
  border: 0px solid rgb(148, 110, 110);
  font-size: 12px;
  }
.tr {
  display: flex;
  width: 100%;
  justify-content: center;
  height: 3rem;
  align-items: center;
}
.td {
  width:40%;
  justify-content: center;
  text-align: center;
}
.bg-w{
  background: rgb(224, 185, 185);
} 
.th {
  width: 60%;
  justify-content: center;
  background: #5b75c2;
  color: rgb(247, 242, 242);
  display: flex;
  height: 5rem;
  align-items: center;
}

json代码

{
  "usingComponents": {}
}

以上是我的功能分享,感兴趣的可以试一试。 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值