如何解决在 Ember.js 中,您如何扩展组件并在 did-insert 上触发操作?
我们的项目目前使用 Ember 3.12,我们正在尝试升级到使用 Ember 3.20,但我们在扩展 ember-power-select 组件(现在使用 Glimmer 组件)时遇到问题。在我们的扩展组件中,我们需要在插入组件并访问组件元素时调用一个方法,我们在 Ember 3.12 中使用 didInsertElement 做到了这一点,但我们现在需要使用 did-insert 修饰符。但是,当我们创建自己的模板文件,其中包含触发 did-insert 修饰符的元素时,不会显示 power-select 元素(因为我们的模板文件已替换它)。我宁愿不将 power-select.hbs 文件的全部内容复制到我们自己的文件中,并将其包装在包含 did-insert 修饰符的 div 中,以便我们可以访问操作中的组件元素。这种情况有模式吗?现在可以扩展像模板一样,还是有另一种方法可以在插入组件时触发操作(并且仍然可以访问组件的元素)?
解决方法
我建议不要通过从其 JavaScript 类扩展来扩展 Ember Octance 中的组件。而是调用包装组件模板中的组件:
{{! app/component/wrapper-around-ember-power-select.hbs }}
<PowerSelect
{{! passthrough all arguments you want to support }}
@selected={{@selected}}
@options={{@options}}
@onChange={{@onChange}}
{{! register your own modifier }}
{{did-insert this.onEmberPowerSelectInsertIntoDom}}
{{! set some HTML attributes }}
class="foo"
/>
// app/component/wrapper-around-ember-power-select.js
import Component from '@glimmer/component';
import { action } from '@ember/object';
export default class WrapperAroundEmberPowerSelectComponent extends Component {
@action
onEmberPowerSelectInsertIntoDom(element) {
// do something with the element
}
}
以这种方式扩展组件的好处是仅使用其公共 API。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。