在首页明细这里,通过相加后变化数据的支出部分,将他的数据动态的传递给另一个页面,麻烦用代码讲讲,因为支出总额要随下面增加的账单而变化,用全局变量能实现吗?


在首页明细这里,通过相加后变化数据的支出部分,将他的数据动态的传递给另一个页面,麻烦用代码讲讲,因为支出总额要随下面增加的账单而变化,用全局变量能实现吗?


关注Hi~ 少年我又带着不是最优解的案例来了。
简陋的效果:

粗糙的代码:
index/index.wxml
<view>总支出: {{totalExpenditure}} 元</view>
<view>支出条目</view>
<view wx:for="{{billFlow}}" wx:key="unique">
{{item.content}} {{item.price}}元
</view>
index/index.js
const app = getApp()
Page({
data: {
totalExpenditure: 0,
billFlow: []
},
onShow() {
this.setData({
totalExpenditure: app.totalExpenditure(),
billFlow: app.billFlow
})
}
})
index2/index.wxml
<view>剩余预算: {{remainingBudget}}</view>
<view>本月预算: {{budget}}</view>
<view>本月支出: {{totalExpenditure}}</view>
<view bindtap="pay" wx:for="{{goods}}" wx:key="unique" data-price="{{item.price}}" data-content="{{item.content}}">买{{item.content}} {{item.price}} 元</view>
index2/index.js
const app = getApp()
Page({
data: {
totalExpenditure: 0,
remainingBudget: 0,
budget: 0,
billFlow: [],
goods: [
{
content: '棒棒糖',
price: 1,
},
{
content: '口香糖',
price: 2,
}
]
},
onShow() {
this.setData({
totalExpenditure: app.totalExpenditure(),
billFlow: app.billFlow,
budget: app.budget,
remainingBudget: app.remainingBudget()
})
},
pay(e) {
const { price, content } = e.currentTarget.dataset;
app.billFlow.push({
content,
price: -1 * price
})
this.onShow()
}
})
app.js
App({
// 预算
budget: 100,
// 账单流水
billFlow: [
{
content: '餐饮',
price: -73
}
],
// 总支出
totalExpenditure() {
return Math.abs(this.billFlow.filter(f => f.price < 0).reduce((t, i) => t + i.price, 0))
},
// 剩余预算
remainingBudget(){
return this.budget - this.totalExpenditure();
}
})