常用功能
1.获取用户信息
index.wxml中
<button open-type="getUserInfo" bindgetuserinfo='getUserInfo'>登录</button>
index.js中
getUserInfo: function(e) {
// console.log(e)
// console.log(e.detail.userInfo)
}
open-type 的合法值 :getUserInfo 获取用户信息,可以从bindgetuserinfo回调中获取到用户信息
2.获取用户openid
-
初始化
#1 project.config.json中配置云函数目录 "cloudfunctionRoot": "./cloudFn", #2 在根目录下创建文件cloudFn #3 app.js中的onLaunch里面添加代码 wx.cloud.init({ env:"test-111" //test-111为云开发当前环境,到自己的云开发环境进行替换 })
-
创建云函数getOpenid
// 云函数入口文件 const cloud = require('wx-server-sdk') cloud.init() // 云函数入口函数 exports.main = async (event, context) => { let { OPENID, APPID, UNIONID } = cloud.getWXContext() return { OPENID, APPID, UNIONID, } }
-
调用云函数获取用户openid
//index.js中的getUserInfo中 wx.cloud.callFunction({ name:'getOpenid', //云函数的名字 success:res=>{ //console.log(res) console.log(res.result.OPENID) //打印用户openid }, fail:console.error })
3.保存和读取到缓存中的数据
保存
wx.setStorageSync(string key, any data)
//示例代码 'userInfo'为key "小王"为值
wx.setStorageSync('userName', "小王")
读取
var value = wx.getStorageSync('userName')
4.页面js中的数据保存
例如在index.js中
Page({
data: {
userInfo: {},
hasUserInfo: false,
canIUse: wx.canIUse('button.open-type.getUserInfo')
},
onLoad: function () {
this.setData({
userInfo: "testName",
hasUserInfo: true
})
}
})
在Page里面函数中使用this.setData({})更新Page中data的数据
5.页面跳转
https://developers.weixin.qq.com/miniprogram/dev/api/route/wx.switchTab.html 中路由
小程序开发文档=> API=>路由
wx.navigateTo({
url: '/pages/index/index'
})
6.读取云环境的数据
https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/database/init.html 查看文档
//初始化
const testDB = wx.cloud.database({
env: 'test' // 'test'为自己的云开发环境
})
//到文档中查看相应的操作文档