Aurelia框架下视图模型间值传递问题:如何将视图2的选择框值传递到视图1
Let's break down what's going wrong and fix it step by step:
The Core Issue
In your View 1, you're binding the child component's selected-option to optionTypes.selectedOption—this is referencing the child component instance's property directly, not linking it to your parent component's own selectedOption property. That's why your parent's selectedOption stays undefined.
Step 1: Correct the Parent Component Binding
Update View 1's HTML to bind the child's selected-option directly to your parent's selectedOption property. This creates a two-way binding that syncs values between parent and child:
<template> <require from="../../Options/Options"></require> <!-- Bind to the parent's own selectedOption, not the child instance's property --> <options selected-option.bind="selectedOption" view-model.ref="optionTypesInstance"></options> <!-- Add this to test if the value is updating in the parent --> <p>Selected Value (from Parent): ${selectedOption}</p> </template>
Your View 1 TypeScript stays mostly the same—just ensure the property exists:
public selectedOption: string;
Step 2: Ensure Two-Way Binding in the Child
While Aurelia sometimes infers two-way binding for form controls, explicitly setting it on your child's bindable property makes the behavior reliable. Update your child component (View 2) TypeScript:
import { bindable, Component } from 'aurelia-framework'; // Use PascalCase for class names (standard TypeScript convention) export class OptionTypes extends Component { // Explicitly set two-way binding mode @bindable({ mode: 'two-way' }) selectedOption: string = ''; sOptions = ["1", "2", "3"]; async displayOption() { console.log('Selected option in child:', this.selectedOption); // At this point, the parent's selectedOption is already synced } }
Step 3: Verify the Child's Select Binding
Your View 2 HTML is mostly correct, but double-check that the value.bind on the select and options is set properly (which it is). When a user selects an option, the child's selectedOption updates, and the two-way binding pushes that value up to the parent.
Why This Works
- By binding the child's
selected-optionto the parent'sselectedOption, you create a direct link between the two properties. - The
@bindable({ mode: 'two-way' })decorator ensures that any change to the child'sselectedOptionis automatically reflected in the parent's property. - You can use the
view-model.refto reference the child instance if you need to call methods on it later, but it's not required for value syncing.
Test this out by selecting an option in the dropdown—you should see the value update in the parent's <p> element immediately, and your parent's selectedOption property will hold the correct value.
内容的提问来源于stack exchange,提问作者deanpillow

