js文件
// miniprogram/pages/carPage.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
itemList: [],
openid: '',
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
if (app.globalData.openid) {
this.setData({
openid: app.globalData.openid
})
}
this.onQuery();
},
//查询数据库
onQuery: function () {
//打开数据库
const db = wx.cloud.database()
//打开对应表
let table = db.collection('cars')
//查找数据
table.where({
_openid: this.data.openid
}).get({
success: res => {
console.log(res.data);
this.setData({
itemList: res.data
})
},
fail: err => {
wx.showToast({
icon: 'none',
title: '查询记录失败'
})
console.error('[数据库] [查询记录] 失败:', err)
}
})
},
//数据库更新数据
selectedAction: function (e) {
var index = e.currentTarget.dataset.index;
var item = this.data.itemList[index];
var that = this;
//打开数据库
const db = wx.cloud.database()
//打开对应表
let table = db.collection('cars')
table.doc(item._id).update({
data:{
islike:!item.islike
},
success:res =>{
item.islike = !item.islike;
that.setData({
itemList: that.data.itemList,
});
},
fail: err => {
icon: 'none',
console.error('[数据库] [更新记录] 失败:', err)
}
})
},
//数据库删除数据
deleteAction: function (e) {
var index = e.currentTarget.dataset.index;
var item = this.data.itemList[index];
var that = this;
//根据id删除数据
if(item._id){
//打开数据库
const db = wx.cloud.database()
//打开对应表
let table = db.collection('cars')
table.doc(item._id).remove({
success:res =>{
//删除本地数据
that.data.itemList.splice(index,1)
that.setData({
itemList: that.data.itemList,
})
wx.showToast({
title: '删除成功',
})
},
fail: err => {
wx.showToast({
icon: 'none',
title: '删除失败',
})
console.error('[数据库] [删除记录] 失败:', err)
}
})
}
},
//数据库添加数据
addAction: function () {
//获取随机数
var number = Math.floor(Math.random()*500);
//打开数据库
const db = wx.cloud.database()
//打开对应表
let table = db.collection('cars')
var that = this;
//模拟数据
var addItem = {
name:'奥迪',
islike:false,
type: 'A' + number.toString()
}
table.add({
//向数据库添加
data:addItem,
success:res =>{
//向本地添加
addItem._id = res._id;//本地数据赋值_id
that.setData({
itemList: that.data.itemList.concat(addItem),
})
wx.showToast({
title: '新增记录成功',
})
},
fail: err => {
wx.showToast({
icon: 'none',
title: '新增记录失败'
})
console.error('[数据库] [新增记录] 失败:', err)
}
})
},
})
wxml文件
wxss文件
/* miniprogram/pages/carPage.wxss */
.item_container{
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
padding: 15px;
height: 30px;
background-color: white;
margin-bottom: 2px;
}
.left_container{
display: flex;
align-items: center;
}
.icon{
width: 20px;
height: 20px;
}
.text{
color: black;
font-size: 18px;
margin-left: 15px;
margin-right: 20px;
}
.btn_container{
display: flex;
justify-content: center;
}
.button{
background-color: red;
width: 80% !important;
color: white;
margin-top: 20px;
margin-bottom: 20px;
}