当前位置:网站首页>微信小程序自定义组件的计算属性功能
微信小程序自定义组件的计算属性功能
2022-08-05 22:30:00 【高级前端工程师全站方向】
1、behavior.js
module.exports = Behavior({
lifetimes: {
created() {
this._originalSetData = this.setData // 原始 setData
this.setData = this._setData // 封装后的 setData
}
},
definitionFilter(defFields) {
const computed = defFields.computed || {}
const computedKeys = Object.keys(computed)
const computedCache = {}
// 计算 computed
const calcComputed = (scope, insertToData) => {
const needUpdate = {}
const data = defFields.data = defFields.data || {}
for (let key of computedKeys) {
const value = computed[key].call(scope) // 计算新值
if (computedCache[key] !== value) needUpdate[key] = computedCache[key] = value
if (insertToData) data[key] = needUpdate[key] // 直接插入到 data 中,初始化时才需要的操作
}
return needUpdate
}
// 重写 setData 方法
defFields.methods = defFields.methods || {}
defFields.methods._setData = function (data, callback) {
const originalSetData = this._originalSetData // 原始 setData
originalSetData.call(this, data, callback) // 做 data 的 setData
const needUpdate = calcComputed(this) // 计算 computed
originalSetData.call(this, needUpdate) // 做 computed 的 setData
}
// 初始化 computed
calcComputed(defFields, true) // 计算 computed
}
})2、use.js
const beh = require('./behavior.js')
Component({
behaviors: [beh],
data: {
a: 0,
},
computed: {
b() {
return this.data.a + 100
},
},
methods: {
onTap() {
this.setData({
a: ++this.data.a,
})
}
}
})边栏推荐
猜你喜欢
随机推荐
Merge Sort
七夕节最深情表白文案从此告别搓衣板
论如何下载网页中的m3u8/ts视频
Why can't the expedited fee of 5,000 yuan guarantee the delivery time?
60: Chapter 5: Develop admin management services: 13: Develop new functions of [Add/Modify Friendship Links, Interfaces]; (Add data to MongoDB) (To operate the Dao layer interface of MongoDB, you must
七夕时如何拯救躁动不安的心
ESP8266-Arduino编程实例-红外寻迹传感器驱动
从哪里可以获取到安全的低佣金账号渠道
关于 Invalid prop: type check failed for prop “index“. Expected String, got Undefined
Nanoprobes丨GoldiBlot 用于 His-tag 检测方案
关于 SAP UI5 floating footer 显示与否的单步调试以及使用 SAP UI5 的收益
LSN、Checkpoint?MySQL的崩溃恢复是怎么做的?
MQ的概念
捷报又至!牛辅材斩获“2022年度最佳影响力品牌”大奖!
Is it better to design vias as small as possible?
如何优雅的消除系统重复代码
亿级流量系统架构之如何设计高容错分布式计算系统
解读APS及其效益
IDEA中如何使用debug调试项目 一步一步详细教程
Application Prospect and Application Benefit of APS in Printing Industry









