1. 項目簡介
最近研究小程序雲,上線了一個有關菜品查詢的小程序。包括搜索、分享轉發、收藏、查看歷史記錄等功能。菜譜 API 來自聚合數據。
2. 小程序地址
https://github.com/caochangkui/miniprogram-food
3. 小程序預覽:
4. 部分截圖
首頁
歷史記錄
5. 項目樹
.
├── README.md
├── project.config.json // 項目配置文件
└── cloudfunctions | 雲環境 // 存放雲函數目錄
│ └── login // 雲函數
│ ├── index.js
│ └── package.json
└── miniprogram
├── images // 存放小程序圖片
├── pages // 存放小程序各種頁面
| ├── index // 首頁
| └── menu // 菜單頁
| └── user // 用戶中心
| └── search // 搜索頁
| └── list // 列表頁 搜索結果頁
| └── detail // 詳情頁
| └── databaseGuide // 數據庫指導頁
| └── chooseLib // 提示頁
| └── storageConsole // 文件上傳提示
├── style // 樣式文件目錄
├── app.js // 小程序公用邏輯
├── app.json // 全局配置
├── app.wxss // 全局樣式
6. 歷史記錄和收藏
小程序·雲開發提供了三個基礎能力:數據庫、存儲和雲函數。
雲開發提供了一個 JSON 數據庫,數據庫中的每條記錄都是一個 JSON 格式的對象。一個數據庫可以有多個集合(相當於關係型數據中的表),集合可看做一個 JSON 數組,數組中的每個對象就是一條記錄,記錄的格式是 JSON 對象。
項目中搜索的歷史記錄和用戶收藏的菜品都可以存儲到雲端數據庫。
歷史記錄的添加和刪除:
下面是歷史記錄的處理方法,菜品收藏與其類似。雲開發數據庫的增刪改查詳見官方文檔。
<view class='search'>
<image src='/images/search.png'></image>
<input placeholder='今天吃什麼' focus bindinput="bindKeyInput" bindconfirm='goSearch' ></input>
<text bindtap='goSearch'>搜索</text>
</view>
// pages/search/search.js
Page({
data: {
inputValue: '',
openid: '',
showHistory: true,
historyList: []
},
// 進入搜索結果頁 -> list
goSearch() {
let content = this.data.inputValue
if (!content) {
return
}
this.onHistory(content)
wx.navigateTo({
url: `/pages/list/list?content=${content}`,
})
},
// 添加歷史記錄
onHistory (content) {
const db = wx.cloud.database() // 獲取數據庫引用
let that = this
// 查看是否有歷史記錄
db.collection('food').where({
_openid: this.data.openid,
_id: 'history' + this.data.openid
}).get({
success: res => {
console.log('數據庫查詢成功: ', res)
if (!res.data.length) {
console.log(' 歷史記錄爲空')
let historyArray = []
historyArray.unshift(content)
db.collection('food').add({
data: {
_id: 'history' + that.data.openid,
description: 'history',
historyList: historyArray
}
}).then(res => {
console.log(res)
})
} else {
console.log('已有歷史記錄')
let historyArray = res.data[0].historyList
historyArray.unshift(content)
console.log([...new Set(historyArray)])
db.collection('food').doc('history' + that.data.openid).update({
data: {
historyList: [...new Set(historyArray)]
}
}).then((res) => {
console.log(res)
})
}
},
fail: err => {
wx.showToast({
icon: 'none',
title: '查詢記錄失敗'
})
console.error('數據庫查詢失敗:', err)
}
})
},
// 讀取歷史記錄
getHistory() {
let that = this
const db = wx.cloud.database()
db.collection('food').doc('history' + that.data.openid).get({
success(res) {
console.log(res.data)
that.setData({
historyList: res.data.historyList
})
}
})
},
// 清空歷史記錄
bindClearHistory() {
const db = wx.cloud.database()
db.collection('food').doc('history' + this.data.openid).update({
data: {
historyList: []
}
}).then((res) => {
console.log(res)
wx.showToast({
icon: '刪除',
title: '清空歷史',
})
})
this.setData({
historyList: []
})
}
})