Files
ChowBox/miniapp/pages/recipe-list/recipe-list.js

83 lines
2.2 KiB
JavaScript
Raw Normal View History

const api = require('../../utils/api');
Page({
data: {
showAnimation: false,
dataReady: false,
loading: false,
results: [],
ingredients: []
},
onLoad(options) {
if (options.payload) {
try {
const payload = JSON.parse(decodeURIComponent(options.payload));
const ingredients = payload.ingredients || [];
const staples = payload.staples || [];
this.setData({ ingredients });
this.match(ingredients, staples);
} catch (e) {
wx.showToast({ title: '参数错误', icon: 'none' });
}
}
},
match(ingredients, staples) {
this.setData({
showAnimation: true,
dataReady: false,
results: []
});
api.post('/api/fridge/match', { ingredients: ingredients, staples: staples })
.then((data) => {
this.setData({ results: data, dataReady: true });
if (data.length > 0) {
const history = wx.getStorageSync('box_history') || [];
history.push({
id: Date.now().toString(),
icon: '🥬',
name: data[0].recipe.name + ' (' + data[0].matchRate + '%匹配)',
time: new Date().toLocaleString(),
typeName: '冰箱盲盒'
});
wx.setStorageSync('box_history', history);
}
})
.catch(() => {
this.setData({
showAnimation: false,
results: [],
loading: false
});
wx.showToast({ title: '匹配失败,请重试', icon: 'none' });
});
},
onAnimationDone() {
this.setData({ showAnimation: false });
},
goDetail(e) {
const id = e.currentTarget.dataset.id;
let missing = e.currentTarget.dataset.missing;
// dataset 值可能是字符串,需要解析
if (typeof missing === 'string') {
try { missing = JSON.parse(missing); } catch (e) { missing = []; }
}
if (!Array.isArray(missing)) missing = [];
let url = '/pages/recipe-detail/recipe-detail?id=' + id;
if (missing.length > 0) {
url += '&missing=' + encodeURIComponent(JSON.stringify(missing));
}
wx.navigateTo({ url: url });
},
reshuffle() {
this.match(this.data.ingredients);
}
});