HTML中组件被卸载后还可以调用到JS方法

微信小程序开发


同一页面有两个组件,两个组件有一个相同的方法。
组件使用behavior吧整个Component对象引入page.js
当页面调用组件的log时,会调用到两个组件的方法


求诸君解惑:为什么WXML都卸载了组件B但是可以调用B的方法?

<view>
  <componentA wx:if={{show}} />
  <componentB wx:if={{!show}} />
view>
// componentA.js
Componen({
  log() {
    console.log('A');
  }
})
// componentB.js
Componen({
  log() {
    console.log('B');
  }
})
// page.js
page({
  behaviors: [behavior],

  data: {
    show: true
  },
  ...
  componentsArray: [componentA, componentB],
  ...

  this.componentsArray.forEach(item => {
    item.log();
  })
  // A
  // B
})

以下答案引用自GPT-3大模型,请合理使用:
componentA和componentB的log方法都会执行。WXML卸载了componentA,但是可以调用componentA的log方法。因为Page.js中已经将componentA的behaviors集合引入了,所以会调用到componentA的log方法。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^