当前位置:   article > 正文

微信小程序万能模板(tabBar\openid\授权登录\云开发之一个云函数实现云数据库增删查改!)_微信小程序增删改查模板

微信小程序增删改查模板

Step1:新建小程序

  1. 使用自己的appid
  2. 勾选不使用云服务(后面可以在项目中再使用,这里若勾选会多出很多乱七八糟的东西)
  3. 选择不使用模板

Step2:搭建tabBar

在这里插入图片描述

  1. 从阿里巴巴图标库https://www.iconfont.cn/下载需要的图标,保存到icons文件夹中。
  2. app.json中和window同层级添加tabBar,并修改“pages”包含的page.
    (pages代码中删去了index和log页面,但文件夹依然存在,可以选中点击右键手动删去)
 "pages": [
    "pages/homepage/homepage",
    "pages/my/my",
    "pages/other/other"
  ],
  ...
  "tabBar": {
    "color": "#999",
    "selectedColor": "63B8FF",
    "list": [
      {
        "pagePath": "pages/other/other",
        "text": "其它",
        "iconPath": "icons/其它.png",
        "selectedIconPath": "icons/其它selected.png"
      },
      {
        "pagePath": "pages/homepage/homepage",
        "text": "消息",
        "iconPath": "icons/首页.png",
        "selectedIconPath": "icons/首页selected.png"
      },
      {
        "pagePath": "pages/my/my",
        "text": "我的",
        "iconPath": "icons/我的.png",
        "selectedIconPath": "icons/我的selected.png"
      }
    ]
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

Step3:通过云函数获取用户openid

  1. 云环境初始化
    首先,从云开发控制台获取到云环境id
    然后,在app.js写入以下代码中初始化云环境
onLaunch() {
    //云环境初始化
    wx.cloud.init({
      env:'云环境id',//改为自己的云环境id
      traceUser: true,
    })
    ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. 创建云函数

首先,在project.config.json中添加cloudfunctions

{
    "cloudfunctionRoot": "cloudfunctions/",
    ...
  • 1
  • 2
  • 3

新建云函数
在这里插入图片描述

修改云函数的index.js文件

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

cloud.init()

//获取用户的openid
exports.main = async(event, context) => {
 return event.userInfo; //返回用户信息
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

上传并部署
在这里插入图片描述3.将openid设置为全局变量

修改app.js文件

onLaunch() {
...
this.getOpenid();
  },

  getOpenid() { 
    wx.cloud.callFunction({
     name: 'getOpenid',
     complete: res => {
      console.log('云函数获取到的openid: ', res.result.openid)//!注意:这里openid的i可能是大写也可能是小写,具体的可以先在控制台打印res.result查看
      this.globalData.openid=res.result.openid
   },
  })
},
  globalData: {
    openid:""
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

Step4:授权登录

在这里插入图片描述在这里插入图片描述

my.wxml

<!-- userInfo如果为空证明没有登录 -->
<button wx-if="{{!userInfo}}" bindtap="login">获取头像昵称</button>
<view wx:else class="userInfo">
    <image src="{{userInfo.avatarUrl}}"></image>
    <text>{{userInfo.nickName}}</text>
</view>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

my.js

Page({
    data: {
        userInfo: '', //用于存放获取的用户信息
    },
    login() {
        wx.getUserProfile({
            desc: '必须授权才能继续使用', // 必填 声明获取用户个人信息后的用途,后续会展示在弹窗中
            success:(res)=> { 
                console.log('授权成功', res);
                this.setData({ 
                    userInfo:res.userInfo
                })
            },
            fail:(err)=> {
                console.log('授权失败', err);
            }
        })
    },
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

my.wxss

.userInfo{
    display: flex;
    flex-direction: column;
    align-items: center;
}
.userInfo image{
    width: 200rpx;
    height: 200rpx;
    border-radius: 200rpx;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

my.json

{
  "usingComponents": {},
  "navigationBarTitleText":"登录" 
}
  • 1
  • 2
  • 3
  • 4

Step5:一个云函数实现云数据库的增删查改

云函数测试集合collection名称为test,记录如下
在这里插入图片描述

在这里插入图片描述

1.创建云函数dbManipulation

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

cloud.init()
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
    console.log("云函数event", event)
    return RESULT(event)
}

(云函数代码不完整)
···这里有一段核心代码(是RESULT函数的具体实现)...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

上传并部署好
2.修改utils.js文件

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}
//弹窗提示
function tips(title='',time=1500,icon='none') {
  wx.showToast({
    title: title,
    time:time,
    icon:icon
  })  
}
//弹窗确认提示
function confirm(content='',callback) {
  wx.showModal({
    title:'温馨提示',
    content:content,
    success:function(res) {
      callback(res);
    }
  })  
}
//云函数请求
function cloudRequest(name,data,callback) {
  wx.showLoading({
    title: '',
  })
  wx.cloud.callFunction({
    name:name,
    data:data,
    success:res=>{
      wx.hideLoading();
      callback(res);
    },
    fail:err=>{
      console.log(err);
      wx.hideLoading();
    }
  })
} 

module.exports = {
  formatTime,
  tips:tips,
  confirm:confirm,
  cloudRequest:cloudRequest
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

运用案例(e.g.主页)
homepage.wxml

<view>数据库查询结果</view>
<view wx:for="{{testList}}">
    <view>{{item.name}}</view>
</view>
<button bindtap="add">增加“C</button>
<button bindtap="delete" data-name="Python">删除“Python</button>
<button bindtap="update" data-id="eb860d36634e87d900ccb62b24c3bfc0">传入“R”的_id,改为Matlab</button>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

homepage.js

import{tips,confirm,cloudRequest} from '../../utils/util.js'
Page({
    data: {~~删除线格式~~ 
        testList: [],
    },
    onLoad: function (options) {
        this.getTestList();//调用函数查询数据库内容
    },
    //数据库增加记录
    add(){
        cloudRequest('dbManipulation', {
            module: 'test',//集合名称
            action: 'add',//操作
            params: {name:"C"}
        }, function (res) {
            console.log('add-res', res)
        })
        this.getTestList();//更新后刷新数据
    },
    //数据库删除记录
    delete(e){
        const {name}=e.currentTarget.dataset;
        cloudRequest('dbManipulation', {
            module: 'test',//集合名称
            action: 'delete',//操作
            map: {name:name}
        }, function (res) {
            console.log('remove-res', res)
        })
        this.getTestList();//更新后刷新数据
    },
    //数据库修改记录
    update(e){
        const {id}=e.currentTarget.dataset;
        cloudRequest('dbManipulation', {
            module: 'test',//集合名称
            action: 'update',//操作
            id:id,
            params: {name:"Matlab"}
        }, function (res) {
            console.log('update-res', res)
        })
        this.getTestList();//更新后刷新数据
    },
    //数据库查询
    getTestList() {
        var that = this;
        cloudRequest('dbManipulation', {
            module: 'test',//集合名称
            action: 'query',//操作
            map: {}
        }, function (res) {
            console.log('查询得到的数据res', res)
            that.setData({
                testList:res.result.data
            })
        })
    },
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/466669
推荐阅读
相关标签
  

闽ICP备14008679号