【小程序】基础知识

项目稍后会上传到github上,需要的可以私聊查看,都是一些基础api使用。

登陆

button按钮上面的open-type设置为getUserInfo,则可以让用户点击按钮时候进行授权,然后通过当前button的bindgetuserinfo属性设置回调方法,bindgetuserinfo的参数就是用户的信息。

<button 
	open-type="getUserInfo" 
	bindgetuserinfo="userLogin" 
	size="mini" 
	type="primary"
>登陆</button>

上拉加载

onReachBottom函数
在 json 文件内可以进行配置,onReachBottomDistance 设置距离底部距离进行加载

onReachBottom: function () {
    this.setData({
      page: this.data.page + 1
    },()=>{
      this.getList()
    })
  },

下拉刷新

onPullDownRefresh函数
默认是不开启下拉刷新功能,需要在json文件设置enablePullDownRefresh:true 开启下拉刷新功能。
需要注意的是,下拉刷新动画只有在调用wx.stopPullDownRefresh时候才会停止。

onPullDownRefresh: function () {
    this.setData({
      page: 0
    },()=>{
      this.getList()
    })
  },

使用数据库

云开发的时候有云数据库,可以进行数据存储,切微信云数据库语法和mongodb很像

初始化连接数据库

const db = wx.cloud.database()

基本的增删改查

增 add

默认会为数据添加_id,_openid,create_time字段
data为新增的数据字段
success为数据插入成功后的回调,参数是一个对象包含插入数据的_id

db.collection('todos').add({
  // data 字段表示需新增的 JSON 数据
  data: {
    // _id: 'todo-identifiant-aleatoire', // 可选自定义 _id,在此处场景下用数据库自动分配的就可以了
    description: "learn cloud database",
    due: new Date("2018-09-01"),
    tags: [
      "cloud",
      "database"
    ],
    // 为待办事项添加一个地理位置(113°E,23°N)
    location: new db.Geo.Point(113, 23),
    done: false
  },
  success: function(res) {
    // res 是一个对象,其中有 _id 字段标记刚创建的记录的 id
    console.log(res)
  }
})
删 remove

根据remove()前面的查询条件进行删除

const cloud = require('wx-server-sdk')
const db = cloud.database()
const _ = db.command

exports.main = async (event, context) => {
  try {
    return await db.collection('todos').where({
      done: true
    }).remove()
  } catch(e) {
    console.error(e)
  }
}
改 update
db.collection('todos').doc('todo-identifiant-aleatoire').update({
  // data 传入需要局部更新的数据
  data: {
    // 表示将 done 字段置为 true
    done: true
  },
  success: function(res) {
    console.log(res.data)
  }
})

// 数据自增
const _ = db.command
db.collection('todos').doc('todo-identifiant-aleatoire').update({
  data: {
    // 表示指示数据库将字段自增 10
    progress: _.inc(10)
  },
  success: function(res) {
    console.log(res.data)
  }
})

update方法为更新数据,其中还有对数据进行额外操作的属性,比如在原始值进行自增、移除等需要使用到原数据的操作,提供了下面属性进行配合使用。

在这里插入图片描述

where表示查询条件,符合条件的数据项会组成一个数组,在success中被当做参数res返回。

db.collection('todos').where({
  // gt 方法用于指定一个 "大于" 条件,此处 _.gt(30) 是一个 "大于 30" 的条件
  progress: _.gt(30)
})
.get({
  success: function(res) {
    console.log(res.data)
  }
})

// 获取单条记录,使用doc
db.collection('todos').doc('todo-identifiant-aleatoire').get({
  success: function(res) {
    // res.data 包含该记录的数据
    console.log(res.data)
  }
})

在这里插入图片描述
在查询条件中常常有对某一项条件做多种限制,比如返回某项数据条件大于20小于40,此时需要用到查询指令。
使用and逻辑查询可以设置多个条件

const _ = db.command
db.collection('todos').where({
  // and 方法用于指定一个 "与" 条件,此处表示需同时满足 _.gt(30) 和 _.lt(70) 两个条件
  progress: _.gt(30).and(_.lt(70))
})
.get({
  success: function(res) {
    console.log(res.data)
  }
})

使用云函数

若使用云能力时候需要在app.js中初始化云能力,云函数的运行环境是 Node.js

App({
  onLaunch: function () {
    
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        // env 参数说明:
        //   env 参数决定接下来小程序发起的云开发调用(wx.cloud.xxx)会默认请求到哪个云环境的资源
        //   此处请填入环境 ID, 环境 ID 可打开云控制台查看
        //   如不填则使用默认环境(第一个创建的环境)
        // env: 'my-env-id',
        env: 'dev-jlpma',
        traceUser: true,
      })
    }

    this.globalData = {}
  }
})

云函数最经典的用法就是获取用户唯一标识,openid
使用wx.getWXContext() 获取用户信息
每个云函数都必须引入wx-server-sdk,类似一个工具包
每个云函数都是一个js程序,都有一个出口,就是exports.main

// index.js
const cloud = require('wx-server-sdk')
exports.main = (event, context) => {
  // 这里获取到的 openId、 appId 和 unionId 是可信的,注意 unionId 仅在满足 unionId 获取条件时返回
  let { OPENID, APPID, UNIONID } = cloud.getWXContext()

  return {
    OPENID,
    APPID,
    UNIONID,
  }
}
在项目中使用云函数:

登陆

const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = (event, context) => {
  const wxContext = cloud.getWXContext()

  return {
    openid: wxContext.OPENID,
  }
}

获取豆瓣图书信息
借助cheerio插件来获取网页dom内容
doubanbook用来对douban书本信息的加密文本进行解密

// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios')
const cheerio = require('cheerio')
const doubanbook = require('doubanbook')

cloud.init()

async function searchDouban(isbn) {
  const url = 'https://search.douban.com/book/subject_search?search_text=' + isbn

  let searchInfo = await axios.get(url)
  let reg = /window\.__DATA__ = "(.*)"/
  if (reg.test(searchInfo.data)) {
    let searchData = doubanbook(RegExp.$1)[0]
    return searchData
  }
}

async function getDouban(isbn) {
  const detailInfo = await searchDouban(isbn)
  const detailPage = await axios.get(detailInfo.url)
  const $ = cheerio.load(detailPage.data)
  let tags = []
  $('#db-tags-section a.tag').each((i, v) => {
    tags.push({
      title: $(v).text()
    })
  })
  const ret = {
    code: 1,
    tags,
    create_time: new Date().getTime(),
    image: detailInfo.cover_url,
    rate: detailInfo.rating.value,
    url: detailInfo.url,
    title: detailInfo.title,
    summary: $('#link-report .intro').text(),
  }
  // console.log(ret)
  return ret
}

getDouban(9787532781096)
// 云函数入口函数
exports.main = async (event, context) => {
  const { isbn } = event
  console.log(isbn)
  if (isbn) {
    return getDouban(isbn)
  } else {
    return {
      code: -1,
      msg: '请扫描正确的图书'
    }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值