You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向dom-repeat传递下拉框值,设置初始值为'b'而非默认的'a'

How to Set Initial Selected Value to 'b' Instead of Default 'a' in dom-repeat-powered Dropdown

Got it, let's work through this. The key here is to bind your dropdown's selected state to a configurable property in your child component, then pass your desired initial value ('b') from the parent. Here's a step-by-step breakdown:

1. Update the Child Component to Expose a Bindable Selected Property

First, modify your child component to define a selectedValue property (or whatever name makes sense for your use case) that controls the dropdown's selection. This replaces the implicit default of picking the first item in your array.

<!-- child-dropdown.html -->
<dom-module id="child-dropdown">
  <template>
    <select selected="{{selectedValue}}">
      <dom-repeat items="{{dropdownOptions}}">
        <template>
          <option value="{{item}}">{{item}}</option>
        </template>
      </dom-repeat>
    </select>
  </template>
  <script>
    Polymer({
      is: 'child-dropdown',
      properties: {
        // Your array of options (could be passed from parent too)
        dropdownOptions: {
          type: Array,
          value: () => ['a', 'b', 'c']
        },
        // Bindable property for selected value
        selectedValue: {
          type: String,
          value: 'a', // Original default, we'll override this from parent
          notify: true // Add this if you need two-way binding (parent gets updates)
        }
      }
    });
  </script>
</dom-module>

2. Pass the Initial Value from the Parent Component

Now in your parent component, when using the child dropdown, simply pass selected-value="b" to override the child's default 'a' value. Polymer will handle binding this value to the dropdown's selected state as soon as the component renders.

<!-- parent-component.html -->
<child-dropdown selected-value="b"></child-dropdown>

Bonus: Handle Dynamic Options (If Needed)

If your dropdownOptions are loaded dynamically (e.g., fetched from an API), add an observer in the child component to ensure your selected value is valid once the options are ready:

// Inside the child component's Polymer definition
observers: [
  '_validateSelectedValue(dropdownOptions, selectedValue)'
],
_validateSelectedValue(options, selectedVal) {
  // Make sure the selected value exists in the options array
  if (options && selectedVal && !options.includes(selectedVal)) {
    // Fallback to first item if selected value is invalid, or adjust as needed
    this.selectedValue = options[0];
  }
}

This way, even if your options load after the initial component render, the selection will stay consistent with what you passed from the parent.

内容的提问来源于stack exchange,提问作者ang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:13:41