为了更好定制自定义组件的功能,可以使用自定义组件扩展机制。

创新互联公司自2013年创立以来,先为伊州等服务建站,伊州等地企业,进行企业商务咨询服务。为伊州企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
从小程序基础库版本 2.0.5 开始支持。
为了更好的理解扩展后的效果,在此举例说明:
代码示例
在开发者工具中打开
在开发者工具中打开
在 WEB IDE 中打开
// behavior.jsmodule.exports = Behavior({definitionFilter(defFields) {defFields.data.from = 'behavior'}})// component.jsComponent({data: {from: 'component'},behaviors: [require('./behavior.js')],ready() {// 此处会发现输出 behavior 而不是 componentconsole.log(this.data.from)}});
通过例子可以发现,自定义组件的扩展其实就是提供了修改自定义组件定义段的能力。
Behavior() 构造器提供了新的定义段 definitionFilter,用于支持自定义组件扩展。 definitionFilter 是一个函数,在被调用时会注入两个参数:
代码示例
在开发者工具中打开
在开发者工具中打开
在 WEB IDE 中打开
// behavior3.jsmodule.exports = Behavior({definitionFilter(defFields, definitionFilterArr) {}});// behavior2.jsmodule.exports = Behavior({behaviors: [require('./behavior3.js')],definitionFilter(defFields, definitionFilterArr) {// definitionFilterArr[0](defFields)}});// behavior1.jsmodule.exports = Behavior({behaviors: [require('./behavior2.js')],definitionFilter(defFields, definitionFilterArr) {}});// component.jsComponent({behaviors: [require('./behavior1.js')]});
说明:
上述代码中声明了 1 个自定义组件和 3 个 behavior,每个 behavior 都使用了 definitionFilter 定义段。按照声明的顺序会有如下事情发生:
definitionFilterArr[0] 即为 behavior3 的 definitionFilter 函数,因为 behavior2 使用了 behavior3。用户在此处可以自行决定在进行 behavior1 的声明时要不要调用 behavior3 的 definitionFilter 函数,如果需要调用,在此处补充代码 definitionFilterArr[0](defFields) 即可,definitionFilterArr 参数会由基础库补充传入。简单概括,definitionFilter 函数可以理解为当 A 使用了 B 时,A 声明就会调用 B 的 definitionFilter 函数并传入 A 的定义对象让 B 去过滤。此时如果 B 还使用了 C 和 D,那么 B 可以自行决定要不要调用 C 和 D 的 definitionFilter 函数去过滤 A 的定义对象。
下面利用扩展简单实现自定义组件的计算属性功能:
代码示例
在开发者工具中打开
在开发者工具中打开
在 WEB IDE 中打开
// behavior1.jsmodule.exports = Behavior({lifetimes: {created() {// 原始 setDatathis._originalSetData = this.setData// 封装后的 setDatathis.setData = this.methods._setData}},definitionFilter(defFields) {const computed = defFields.computed || {}const computedKeys = Object.keys(computed)const computedCache = {}// 计算 computedconst 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// 直接插入到 data 中,初始化时才需要的操作if (insertToData) data[key] = needUpdate[key]}return needUpdate}// 重写 setData 方法defFields.methods = defFields.methods || {}defFields.methods._setData = function (data, callback) {// 原始 setDataconst originalSetData = this._originalSetData// 做 data 的 setDataoriginalSetData.call(this, data, callback)// 计算 computedconst needUpdate = calcComputed(this)// 做 computed 的 setDataoriginalSetData.call(this, needUpdate)}// 初始化 computed// 计算 computedcalcComputed(defFields, true)}})
// 在组件js中const beh = require('./behavior1.js')Component({behaviors: [beh],data: {a: 0,},computed: {b() {return this.data.a + 100},},methods: {onTap() {this._originalSetData({a: ++this.data.a,})}}})
data: {{a}} computed: {{b}}