小程序常用相关

小程序官方api

1. 全局配置

app.json中配置导航(头部),tabbar内容和样式

{
  "pages": [
    "pages/tui/tui",
    "pages/user/user",
    "pages/chat/chat",
    "pages/index/index",
    "pages/logs/logs",
    "pages/search/search"
  ],
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#04be02",
    "navigationBarTitleText": "小鸡炖蘑菇",
    "navigationBarTextStyle": "white"
  },
  "tabBar": {
    "color": "#666",
    "selectedColor": "#f00",
    "list": [
      {
        "pagePath": "pages/index/index",
        "iconPath": "/images/icon/home.png",
        "selectedIconPath": "/images/icon/home-ed.png",
        "text": "主页"
      },
      {
        "pagePath": "pages/tui/tui",
        "iconPath": "/images/icon/tuijian.png",
        "selectedIconPath": "/images/icon/tuijian-ed.png",
        "text": "推荐"
      },
      {
        "pagePath": "pages/search/search",
        "iconPath": "/images/icon/search.png",
        "selectedIconPath": "/images/icon/search-ed.png",
        "text": "搜索"
      },
      {
        "pagePath": "pages/chat/chat",
        "iconPath": "/images/icon/liao.png",
        "selectedIconPath": "/images/icon/liao-ed.png",
        "text": "聊天"
      },
      {
        "pagePath": "pages/user/user",
        "iconPath": "/images/icon/user.png",
        "selectedIconPath": "/images/icon/user-ed.png",
        "text": "我的"
      }
    ]
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json"
}

2.列表渲染 wx:for,wx:if

<!--pages/search/search.wxml-->
<text class="txt">少小离家老大回,安能辨我是雄雌</text>
<text class="txt">{{txt}}</text>
<view class="{{className}}" wx:if="{{bol}}">{{txt}}</view>
<text bindtap="changeBol" class="btn">点击</text>
<view>{{arr[0]}}</view>

<view wx:for="{{arr}}">{{item}}</view>

<!--  列表渲染  
item 默认,表示每一个循环的项
index 默认,表示每一个项的索引,从0开始计算
-->
<view wx:for="{{arrObj}}" class="txt">
 {{index}}={{item.name}}
</view>
<!-- 
如果遇多层嵌套,需要给每一层的item设置一个别名使用
wx:for-item="aa" aa 表示别名
如果需要设置index
wx:for-index="i"  i表示index

每一个列表渲染,都需需要添加一个key
wx:key="index" 绑定key的时候,不需要添加插值表达式
 -->
<view wx:for="{{arrObj}}" wx:key="index" class="txt" wx:for-item="aa">
 {{index}}={{aa.name}}
</view>
<!-- 可以把字符串的每一个字符渲染到列表中 -->
<view wx:for="位卑不敢忘忧国">{{item}}</view>

<view wx:if="{{3>5}}">史湘云</view>
<view wx:elif="{{4>5}}">薛宝钗</view>
<view wx:else>王熙凤</view>

3.设置模板(is);外部引入模板import;外部引入模板以外页面代码include;小程序自带xs文件module导出

<!--  设置模板 
使用template 标签
需要给模板设置一个name,通过name关联使用
-->
<template name="myTel">
<view>{{name}}</view>
<view>泣血蝇虫笑苍天</view>
<view>孤帆远影锁白练</view>
</template>
<!-- 使用模板的时候
通过 is 关联 已经创建的模板名称,这样就可以使用创建的模板内容
通过data绑定动态数据,绑定以后,就不需要在模板中书写获取数据中某一个数据的全部格式
例如
如下实例 绑定完obj以后
使用的时候不需要写 obj.name
-->
<template is="myTel" data="{{...obj}}"></template>

<!-- 外部引入模板 
import 和 include
-->
<import src="./tem.wxml"></import>
<template is="temp1"></template>
<!-- 
注意 模板的使用 只能使用引入文件上的模板,如果引入文件中还引入了其他模板,在当前文件中,不能使用 第三个文件中的其他模板
 -->
<!-- <template is="aTem"></template> -->

<!-- 
  include 可以将目标文件除了 <template/> <wxs/> 外的整个代码引入,相当于是拷贝到 include 位置
 -->
<include src="./include.wxml"></include>
<!-- <template is="tem2"></template> -->
<!-- 引入 wxs -->
<wxs src="/wxs/mo.wxs" module="mo1"></wxs>
<view>{{mo1.aa}}</view>
<view>{{mo1.bb}}</view>
<!-- module 用来设置wxs的模块名,使用的时候直接 模块名.数据名 模块名.方法名 

module.exports = {
  aa:aa,
  bb:bb
};导出wxs页面的内容
-->
<wxs module="mo2">
  var aa = "林冲";
  var bb = "鲁智深";
  module.exports = {
    aa:aa,
    bb:bb
  };
</wxs>

<view>{{mo2.aa}}</view>
<view>{{mo2.bb}}</view>

4.组件相关

1.swiper, image
<swiper class="bor"
indicator-dots="true"
indicator-color="#f60"
indicator-active-color="#04be02"
autoplay="true"
interval="2000"
circular="true"
>
  <swiper-item>
    <image src="{{src}}" mode="{{mode[0]}}"></image>
  </swiper-item>
  <swiper-item>
    <image src="{{src}}" mode="{{mode[0]}}"></image>
  </swiper-item>
  <swiper-item>
    <image src="{{src}}" mode="{{mode[0]}}"></image>
  </swiper-item>
</swiper>

<image src="{{src}}" class="bor" mode="{{mode[0]}}"></image>
<image src="{{src}}" class="bor" mode="{{mode[1]}}"></image>
<image src="{{src}}" class="bor" mode="{{mode[2]}}"></image>
<view class="wp" hover-class="hover"></view>
<scroll-view class="wp" scroll-y="true">

//hover-class类hover效果
  <view class="wp" hover-class="hover">一</view>
  <view class="wp" hover-class="hover">览</view>
  <view class="wp" hover-class="hover">纵</view>
  <view class="wp" hover-class="hover">上</view>
  <view class="wp" hover-class="hover">线</view>
</scroll-view>
// pages/user/user.js
Page({
data: {
    mode:['scaleToFill','aspectFit','aspectFill'],
    src:'https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg'
  },
})
2.icon picker progress button checkbox-group
  • icon: type设置点击后的不同状态
  • picker 下拉 三级联动,日期,省市区,自定义选择器
  • progress 进度条
  • button
  • checkbox-group 复选集合
  • keyboard-accessory 设置键盘和内容的距离状态

<!--  滚动选择日期  -->
<picker mode="date" bindchange="getDate">{{time}}</picker>
<!--  滚动选择三级联动  -->
<picker mode="region" bindchange="getAddress">{{region}}</picker>
<!--  滚动选择学生  -->
<picker mode="selector" range="{{arr}}" bindchange="getStudent">{{student}}</picker>

<icon type="success" size="50"></icon>
<icon type="success_no_circle"  size="60"></icon>
<icon type="waiting" size="50"></icon>
<icon type="warn" size="50"></icon>
<icon type="clear" size="50"></icon>
<icon type="clear" size="50" color="#f00"></icon>
<!-- 进度条 -->
<progress 
percent="80"
show-info="true"
color="#f00"
></progress>
<!-- button -->
<button type="primary" size="mini">点击</button>
<button type="primary" loading="true">点击</button>
<!-- <button type="primary" open-type="getUserInfo" bindgetuserinfo="getuserinfo">点击获取用户信息</button> -->
<image src="{{src}}"></image>
<button type="primary" bindtap="getuserinfo">点击获取用户信息</button>

<checkbox-group bindchange="checkboxValue">
  <checkbox color="#f60" value="1" disabled="true">杜兰特</checkbox>
  <checkbox value="2">哈登</checkbox>
  <checkbox value="3">维斯布鲁克</checkbox>
  <checkbox color="#f60" value="4">欧文</checkbox>
  <checkbox color="#f60" value="5">詹姆斯</checkbox>
</checkbox-group>

<input class="bor" type="text" value="" 
placeholder="请输入内容" 
placeholder-style="color:#f60" 
adjust-position="false"
confirm-type="next"
/>
<textarea hold-keyboard="{{false}}">
  <keyboard-accessory class="container" style="height: 50px;">
    <cover-view bindtap="tap" style="flex: 1; background: green;">1</cover-view>
    <cover-view bindtap="tap" style="flex: 1; background: red;">2</cover-view>
  </keyboard-accessory>
</textarea>
// pages/tui/tui.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    src:'',
    time:'选择日期',
    region:'选择地区',
    student:'选择学员',
    arr:['陈旭','王江坤','康总','浩哥']
  },
  getStudent(value){
    //普通选择器,选择的是数组的下标,{value:'1'}
    console.log(value.detail);
    this.setData({
      student: this.data.arr[value.detail.value] //value.detail.value 获取选中的值
    });
  },
  getDate(value){
    console.log(value.detail);
    this.setData({
      time:value.detail.value //value.detail.value 获取选中的值
    });
  },
  getAddress(value){
    console.log(value.detail.value);
    this.setData({
      region:value.detail.value.join('-')
    });
  },
  tap(){
    console.log(123);
  },
  //获取多选框的内容
  checkboxValue(value){
    console.log(value.detail);
  },
  getuserinfo(){
    //获取用户信息,使用 wx.getUserProfile api
    wx.getUserProfile({
      desc:'获取用户信息',
      success:data=>{
        console.log(data);
        this.setData({
          src:data.userInfo.avatarUrl
        });
      }
    });
  },
 
})
3.单选,滑块,Switch 页面跳转
  • radio-group radio 单选
  • slider 滑块
  • switch 开关
  • navigator 跳转
<radio-group bindchange="getRadio">
<radio value="1" checked="true">前端开发</radio>
<radio value="2">挖掘机修理</radio>
<radio value="3">刷大白</radio>
<radio value="4">要饭</radio>
</radio-group>

<!-- 滑块 -->
<slider color="#f60"value="50%" block-size="28"show-value="true" bindchange="silideChange"></slider>

<!-- switch开关 -->
<switch checked="true" color="#f60" bindchange="switchChange"></switch>

<!-- 页面跳转 -->
<!-- 默认跳转到除了tabBar 的某个页面 出现返回按钮 -->
<navigator url="/pages/case/case">case页面</navigator>
<!-- 跳转到taobar页面 并且没有返回 -->
<navigator url="/pages/index/index" open-type="switchTab">首页</navigator>
<!-- 跳转页面没有返回按钮 -->
<navigator url="/pages/index/index" open-type="reLaunch">首页</navigator>
<navigator url="/pages/aa/aa" open-type="reLaunch">a页面</navigator>
<navigator url="/pages/camera/camera">照相机</navigator>
<navigator url="/pages/video/video">视频</navigator>
Page({

  data: {

  },
  getRadio(val) {
    console.log(val.detail);
  }, 
  silideChange(val) {console.log( val.detail);},
  switchChange(val){console.log( val.detail)},
  
})
4.照相机 视频
  • camera
<camera
class="camera"
mode="normal"
device-position="front"
flash="off"
></camera>

<button type="primary" bindtap="takePhoto">拍照</button>

<image src="{{src}}"mode="aspectFill"></image>
data: {
    src: ''
  },
  takePhoto() {
    //执行createCameraContext 的api,返回一个相机内容的实例,
    //该实例方法具有一个takePhoto方法,可以实现拍照功能
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        console.log(res);
        this.setData({
          // 照片的临时存储路径
          src: res.tempImagePath
        })
      }
    })
  }
  • 摄像机及添加弹幕
<text>pages/video/video.wxml</text>
<video class="video" src="{{src}}" danmuList="{{danmuList}}" id="video"></video>

<view class="wp">
  <input type="text" value="{{text}}" placeholder="输入弹幕" bindinput="changeTxt"/>
  <button type="primary" size="mini"  bindtap="send" >发送</button>
</view>
// pages/video/video.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    src: "https://vd2.bdstatic.com/mda-mckktsgs19mqwzxv/v1-hknm/1080p/mda-mckktsgs19mqwzxv.mp4?v_from_s=nj_haokan_4469&auth_key=1624508685-0-0-c0488d15d8d928e8672c37a79e44f4f8&bcevod_channel=searchbox_feed&pd=1&pt=3&abtest=",
    //弹幕是一个数组,数组中的每一项是一个对象,该对象包含三个属性,text表示弹幕文字,color表示文字的颜色,time表示视频第ji秒显示该弹幕
    danmuList: [{ text: 'hahha', color: '#ff0000', time: 1 }, { text: 'hahha', color: '#ff0000', time: 1 }, { text: 'hahha', color: '#ff0000', time: 12 },],
    text: '',
    ctx: null
  },
  send() {
  //点击发送按钮,先取出data的text文字,通过发送弹幕事件ctx.sendDanmu到视频中
  ?time
    var txt = this.data.text
    this.ctx.sendDanmu({
    //固定的text,color两个属性
      text: txt,
      color: color()
    })
    this.setData({
      text: ''
    })
  },
  changeTxt(ev) {
  //input 事件获取input输入的值,然后把内容存储到state中
    console.log(ev.detail.value);
    this.setData({
      text: ev.detail.value
    })
  },
  
  onReady: function () {
  //创建摄像机实例
    this.ctx = wx.createVideoContext('video')

  },

  
})
//添加随机颜色弹幕
function rand(m,n) {
  return Math.floor(Math.random()*(n-m)+m)
}
function color() {
  let r=rand(0,255)
  let g=rand(0,255)
  let b=rand(0,255)
  return `rgb(${r},${g},${b})`
}
5.map地图
<!--pages/map/map.wxml-->
<map
class="map"
longitude="113.570767"
latitude="34.754837"
markers="{{markers}}"
polyline="{{polyline}}"
circles="{{circles}}"
>经纬度</map>

// pages/map/map.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //设置地图标志
    markers: [{
      // 纬度
      latitude: '34.754837',
      // 经度
      longitude: '113.570767',
      // 设置点图标
      iconPath: '/icon/car-ed.png',
      title: '铁炉堡',
      // 图标旋转
      rotate: 90,
      //设置气泡 比title样式多点
      callout: {
        content: '河南省是中华民族不可分割的',
        color: '#ff0',
        bgColor: '#04be02',
        padding: 10,
        borderRadius: 5
      }

    }, {
      latitude: '34.75537',
      longitude: '113.57167',
      iconPath: '/icon/home-ed.png',
      title: '铁炉堡',
      rotate: 220

    }],
    // polyline 绘制路径
    polyline: [{
      // 两点一条实线
      points: [{
        latitude: '34.754837',
        longitude: '113.570767'
      }, {
        latitude: '34.75537',
        longitude: '113.57167'
      }],
      // 设置点的颜色
      color: '#04be02',
      width: 8,
      dottedLine: true
    }],
    //绘制圆形覆盖物
    circles: [{
      latitude: '34.754837',
      longitude: '113.570767',
      //radius  半径
      radius: 100,
      fillColor: '#ff00ff50',
      color: '#f00',
      strokeWidth: 5
    }]
    //填充颜色必须16进制,最后两位也用十六进制表示,表示透明度
    //color 表示描边颜色
    //strokeWidth 描边宽度

  },

 
})
6.api 数据缓存storage
  • wx.canIUse 返回bol判断是否支持 /api基础
  • wx.getSystemInfoSync() 获取手机设备信息
  • wx.setStorageSync(‘name’(key), this.data.txt(value))
    },
<view>{{bol}}</view>
<input class="bor"  type="text" wqe bindinput="changeTxt"/>
<button type="primary" bindtap="setData1">点击添加内容到storage</button>
// pages/chat/chat.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bol: wx.canIUse('CameraContext.onCameraFrame'),
    txt: ''
  },

  onLoad: function (options) {
    //获取系统信息
    console.log(wx.getSystemInfoSync());
  },
  setData1() {
    wx.setStorageSync('name', this.data.txt)
  },
  changeTxt(ev) {
    console.log(ev.detail.value);
    this.setData({
      txt: ev.detail.value
    })
  },
  
})
7.api开放接口获取权限
  <button  bindtap="getUserProfile"> 获取头像昵称 </button>
 getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,
      后续会展示在弹窗中,请谨慎填写
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },

5.component组件

存储公共数据,属性,方法,

js文件中导出数据
module.exports=Behavior({
  data:{
    behaData:'公共数据'
  },
  methods:{
run(){
  console.log('小鸡炖蘑菇');
}
  },
})

在需要调用数据的js文件中引入并注册

//引入公共的方法和数据behaviors
var abc=require('../../common/common')
// 组件的构造器
Component({
//注册
  behaviors:[abc],
  properties: {
    name:String,
    age:Number,
  },
  data: {
    tips: '不忘初心,牢记使命',
    show:'abc-data'
  }
});

在需要使用的wxml页面中即可直接使用全局的数据和方法

<view>姓名:{{name}}</view>
<view>年龄:{{age}}</view>
<view>{{behaData}}</view>
<button bindtap="run">点击</button>

6.点击提示,弹框,设置tabbar红点,背景,修改文字

<text class="button" catchtap="show1">点击显示showToast</text>
<text class="button" catchtap="show2">点击显示showModel</text>
<text class="button" catchtap="show3">点击显示showLoading</text>
<text class="button" catchtap="show4">点击显示showActionSheet</text>
<text class="button" catchtap="show5">点击显示打开小程序弹出框</text>
<text class="button" catchtap="show6">导航栏加载</text>
<text class="button" catchtap="setTitle">导航栏设置标题</text>
<text class="button" catchtap="setbg">设置背景色</text>
<text class="button" catchtap="setHot">设置小红点(消息)</text>
<text class="button" catchtap="hideNav">隐藏导航</text>
<text class="button" catchtap="showNav">显示导航</text>
<text class="button" catchtap="addNav">添加导航</text>

// pages/show/show.js
Page({

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

  },
  show1() {
    //提示信息
    wx.showToast({
      title: '友情提示',
      // icon:'error'
      // icon:'loading',
      image: "/images/a1.jpg"
    })
  },
  show2() {
    wx.showModal({
      title: '确认拱白菜',
      content: '你确认要拱白菜?',
      success: res => {
        if (res.confirm) {
          console.log('点击了确认按钮');
        } else {
          console.log('点击了取消按钮');

        }
      }
    })


  },
  show3() {
    wx.showLoading({
      //设置透明蒙版,防止可以点击别处
      mask:true,
      title: '加载中',
    })
    setTimeout(() => {
      wx.hideLoading({})
    }, 1000);

  },
  show4(){
    wx.showActionSheet({
      itemList:['钟无艳','黄月英','妇好'],
      success:res=>{
        console.log(res);
      }
    })
  },
show5(){
  //暂时没测出来
  wx.enableAlertBeforeUnload({
    message:'欢迎来到我的小程序'
  })
},show6(){
  // 在当前页面显示导航条加载动画
  wx.showNavigationBarLoading();
  setTimeout(() => {
    wx.hideNavigationBarLoading()
  }, 3000);
},setTitle(){
  wx.setNavigationBarTitle({
    title:'老坛酸菜'
  })
},
setHot(){
  wx.showTabBarRedDot({
    index:1
  })
},
hideNav(){
  wx.hideTabBar({
    animation:true
  })
},
showNav(){
  wx.showTabBar({
    animation:true
  })
},
addNav(){
  // 设置更改导航
wx.setTabBarItem({
  text:"日志",
  index:0,
})
},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.setBackgroundColor({
      backgroundColor:'#ff0000',
      backgroundColorTop: '#00ff00'
    })
  },

})在这里插入代码片

7.ajax请求wx.request封装

import URL from './baseURL';
var AJAX = {
  get: (url, data = {}) => {
    return new Promise((resolve, reject) => {
      wx.request({
        method: 'Get',
        url:URL+url,
        data: data,
        success: res => {
          resolve(res)
        },
        fail: () => {
          reject('请求失败')
        }
      })
    })
  },
  post: (url, data = {}) => {
    return new Promise((resolve, reject) => {
      wx.request({
        method: 'post',
        url: URL + url,
        data: data,
        success: res => {
          resolve(res)
        },
        fail: () => {
          reject('请求失败')
        }
      })
    })
  }
}
export default AJAX;

8.登录,获取用户权限,请求权限

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

  /**
   * 页面的初始数据
   */
  data: {
    val:''

  },
  login() {
    //步骤:登录获取用户code, 通过获取用户的code发送给后台获取登录信息。登录成功后,
    先查看用户已授权信息,已经授权过需要的接口,即可直接使用,没有相应的授权功能的话,
    通过wx.authorize允许用户访问需要的接口(这一步还需要在app.json配置允许权限)
    wx.login({
      success: res => {
        //获取code
        console.log(res.code);
        // 如果获取了code,说明用户已经登录,可以向后台发送该code,用来获取用户信息
        if (res.code) {
          // 查看用户已经授权的接口功能
          wx.getSetting({
            success: res => {
              if (!res.authSetting['scope.userLocation']) {
                wx.authorize({
                  //授权获取使用地理位置的权限
                  scope: 'scope.userLocation',
                  success() {
                    // 获取用户地理位置信息
                    wx.getLocation({
                      // 返回gps坐标
                      type: 'wgs84',
                      success(res) {
                        // 纬度
                        const latitude = res.latitude
                        // 经度
                        const longitude = res.longitude
                        //速度
                        const speed = res.speed

                      }
                    })
                  }
                })
              }
              console.log(res.authSetting);
              console.log(res.authSetting['scope.camera']);
              // 如果userLocation的授权信息为false,则可以在用户获取地理位置时进行授权
              console.log(res.authSetting['scope.userLocation']);
            }
          })

        }
      }
    })
  },
  getInfo() {
wx.getUserProfile({
  desc: '获取用户信息',
  // success:res=>{
  //   console.log(res);
  // }
  //可以用promise获取成功
}).then(res=>{
  console.log(res);
})
  },
})
{
app.json
  "pages":[
    "pages/login/login",
    "pages/index/index",
    "pages/logs/logs"
  ],
  "window":{
    "backgroundTextStyle":"light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "Weixin",
    "navigationBarTextStyle":"black"
  },
  "style": "v2",
  "sitemapLocation": "sitemap.json",

  // 配置请求获取地址权限
  "permission":{"scope.userLocation":{
    "desc": "你的位置用关于展示location"
  }}
}

9.data-传值

<button id="ccc" type="primary" bindtap="getAttr" data-aa="陈树湘">点击</button>
js:
  //data-自定义名字 属性的值 如data-aa="" 用以下方式获取
  getAttr(ev) {
    console.log(ev.currentTarget.dataset.aa);
    // 事件委托的时候可以使用
    console.log(ev.target.dataset.aa);
  }

10 小程序双向绑定

<!-- 小程序的双向绑定只支持单数值,不支持里边进行运算 -->
<input type="text" model:value="{{val}}" placeholder="输入内容"/>
<text>{{val}}</text>

11.云开发数据库操作,分页

<view class="tit">
  <text>姓名</text>
  <text>年龄</text>
  <text>性别</text>
  <text>工作</text>
  <text>操作</text>
</view>
<view class="cont" wx:for="{{arr}}" wx:key="index">
  <text>{{item.name}}</text>
  <text>{{item.age}}</text>
  <text>{{item.sex}}</text>
  <text>{{item.job}}</text>
  <view>
    <text bindtap="del" data-id="{{item._id}}">删除</text>
    <text bindtap="edit" data-id="{{item._id}}">编辑</text>
  </view>
</view>

<view class="act">
  <view>
    <label>姓名</label>
    <input type="text" model:value="{{name}}" />
  </view>
  <view>
    <label>年龄</label>
    <input type="text" model:value="{{age}}" />
  </view>
  <view>
    <label>工作</label>
    <input type="text" model:value="{{job}}" />
  </view>
  <view>
    <label>性别</label>
    <radio-group bindchange="getSex">
      <radio value="男" checked="{{sex=='男'}}">男</radio>
      <radio value="女" checked="{{sex=='女'}}">女</radio>
    </radio-group>
  </view>
  <button bindtap="submit" type="primary">提交</button>
</view>

<view>总条数:{{total}}</view>
<button bindtap="getAll" type="primary">获取总条数</button>

// pages/db/db.js
// 获取数据库的引用,也可以称为数据库句柄
const db = wx.cloud.database();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    total:0,
    arr:[],
    name:'',
    age:'',
    job:'',
    sex:'',
    type:'add',
    editId:''
  },
  // 获取选中的性别
  getSex(ev){
    console.log(ev.detail.value);
    this.setData({
      sex:ev.detail.value
    });
  },
  //获取数据表中的内容
  getDataCont(){
    //collection()用来指定操作的哪一个表,get()方法是获取表格的内容,可以是回调函数的格式操作,也可以使用promise风格
    db.collection('users').get().then(res=>{
      console.log(res.data);
      this.setData({
        arr:res.data
      });
    });
  },
  edit(ev){
    let _id = ev.currentTarget.dataset.id;
    //根据id获取到内容,并且反显到输入框
    db.collection('users').where({
      _id:_id
    }).get().then(res=>{
      console.log(res);
      this.setData({
        editId:_id,
        name:res.data[0].name,
        age:res.data[0].age,
        job:res.data[0].job,
        sex:res.data[0].sex,
        type:'edit'
      });
    });
  },
  //删除
  del(ev){
    let _id = ev.currentTarget.dataset.id;
    console.log(_id);
    /*
    where() 设置查询条件,对象的形式
    remove() 根据查询条件删除数据
    */
    console.log(db.collection('users').where({ _id:_id }));

    wx.showModal({
      title:'确认删除',
      content:'您确定要删除吗?',
      success:res=>{
        if(res.confirm){
          db.collection('users').where({
            _id:_id
          }).remove().then(res=>{
            console.log(res.stats.removed);
            if(res.stats.removed){
              this.getDataCont();
              wx.showToast({
                icon:'success',
                title:'删除成功'
              });
            }
          });
        }
      }
    });
  },
  //提交
  submit(){
    if(this.data.type=='add'){ //添加数据
      // 添加数据使用add(),支持回调函数方式和promise方式,要添加的参数通过data属性进行添加
      db.collection('users').add({
        data:{
          name:this.data.name,
          age:Number(this.data.age),
          job:this.data.job,
          sex:this.data.sex
        }
      }).then(res=>{
        this.setData({
          name:'',
          age:'',
          job:'',
          sex:''
        });
        this.getDataCont();
      });
    }else{ //编辑
      db.collection('users').where({
        _id:this.data.editId
      }).update({
        data:{
          name:this.data.name,
          age:Number(this.data.age),
          job:this.data.job,
          sex:this.data.sex
        }
      }).then(res=>{
        console.log(res.stats.updated);
        if(res.stats.updated){
          wx.showToast({
            title: '修改成功',
            success:()=>{
              this.getDataCont();
              this.setData({
                name:'',
                age:'',
                job:'',
                sex:'',
                editId:'',
                type:'add'
              });
            }
          });
        }
      });
    }
  },

  //获取总条数
  getAll(){
    db.collection('users').count().then(res=>{
      console.log(res.total);
      this.setData({
        total:res.total
      });
    });
  },
  onReady: function () {
    this.getDataCont();
  },

})

分页

// pages/find/find.js
const db = wx.cloud.database();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    arr:[],
    pages:{
      num:2, //每页的条数
      page:1, //当前页数
      p:[1]
    }
  },
  
  //根据年龄输出内容
  setContentByAge(){
    //构建查询条件
    const _ = db.command;
    /*
    查询条件(db.command的方法)
    eq(args)  查询 等于 args 的数据
    neq(args)  查询 不等于 args 的数据
    gt(args)  查询 大于 args 的数据
    lt(args)  查询 小于 args 的数据
    in([]) 查询值在包含在给定的数组中的数据
    gte(args) >=args
    lte(args) <=args
    */ 
    /*
    orderBy('age','asc') 查询结果根据 age 升序  asc -> 升序
    orderBy('age','desc') 查询结果根据 age 降序  desc -> 升序
    */ 
    db.collection('users').where({
      age:_.gt(80)
    }).orderBy('age','asc').get().then(res=>{
      console.log(res.data);
      this.setData({
        arr:res.data
      });
    });
  },

  getAll(){
    db.collection('users').skip(2).limit(2).get().then(res=>{
      console.log(res.data);
      this.setData({
        arr:res.data
      });
    });
  },
  fen(ev){
    let p = ev.currentTarget.dataset.page;

    db.collection('users').skip((p-1)*this.data.pages.num).limit(2).get().then(res=>{
      console.log(res.data);
      this.setData({
        arr:res.data
      });
    });
  },
  //设置总共多少页
  setPage(){
    db.collection('users').count().then(res=>{
      let ps = Math.ceil(res.total/this.data.pages.num);
      let psArr = [];
      for(let i=1;i<=ps;i++){
        psArr.push(i);
      }
      console.log(psArr);
      this.setData({
        pages:{
          num:2,
          page:1,
          p:psArr
        }
      });
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.setContentByAge();
    this.setPage();
    this.getAll();
  },
})
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值