Ember Octane版本中如何从父组件访问子组件的selectedOption
Ember Octane:主组件访问子组件selectedOption的解决方案
你可以通过两种方式实现需求,既保留子组件的动作处理逻辑,又让主组件能获取到子组件的selectedOption:
方法1:回调函数传递状态(推荐,符合单向数据流)
这种方式遵循Ember Octane的单向数据流原则,子组件在处理完自身动作后,将选中值传递给主组件。
子组件代码修改
Child-component.js:
import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; export default class ChildComponent extends Component { @tracked listOptions = [{ id: 124, name: 'Mywork' }]; @tracked selectedOption; @action handleSelection(newValue) { this.selectedOption = newValue; // 子组件内部处理动作逻辑(满足你不能在主组件处理动作的要求) this.performInternalAction(); // 将选中值传递给主组件 this.args.onSelection?.(newValue); } performInternalAction() { // 这里写子组件原本的动作逻辑,比如接口请求、状态更新等 console.log('子组件执行内部动作,选中值:', this.selectedOption); } }
Child-component.hbs:
<Button options={{this.listOptions}} selected={{this.selectedOption}} {{on "change" this.handleSelection}} > Submit </Button>
主组件调用
Main-component.hbs:
<ChildComponent @onSelection={{this.handleChildSelection}} />
Main-component.js:
import Component from '@glimmer/component'; import { action } from '@ember/object'; export default class MainComponent extends Component { @action handleChildSelection(selectedValue) { // 主组件拿到选中值后,执行自己的操作 console.log('主组件获取到子组件选中值:', selectedValue); // 这里写主组件需要做的逻辑,比如更新自身状态、展示信息等 } }
方法2:模板引用直接访问子组件属性(适合简单场景)
如果需要主组件直接访问子组件的属性,可以使用Octane的模板引用功能,不过这种方式会增加组件间耦合,谨慎使用。
主组件代码调整
Main-component.hbs:
<ChildComponent {{ref "childComponent"}} /> {{!-- 在模板中直接访问子组件的选中值 --}} <p>子组件当前选中值:{{this.childComponent.selectedOption}}</p>
Main-component.js:
import Component from '@glimmer/component'; import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; export default class MainComponent extends Component { @tracked childComponent; @action checkSelectedValue() { // 在主组件的动作中访问子组件的选中值 console.log('子组件选中值:', this.childComponent?.selectedOption); } }
关键说明
- 确保子组件的
selectedOption使用@tracked装饰器,这样状态变化时主组件能实时感知到。 - 方法1是官方推荐的方式,避免组件间耦合,更易维护;方法2仅适合简单场景,不推荐在复杂项目中使用。
内容的提问来源于stack exchange,提问作者Kumar
相关产品推荐
相关产品推荐

