簡體   English   中英

如何根據用戶選擇從數組中獲取值?

[英]How to get value from an array based on the user selection?

我遵循了 ember-paper guide 並定義了如下的選項數據。 用戶可以從選項中選擇任何國家。

  timeZoneOptions: Object.freeze([
    { groupName: "Asia", options:["Kabul","Yerevan","Baku","Dhaka","Brunei","Bangkok","Shanghai","Urumqi","Taipei","Macau","Tbilisi","Dili","Kolkata","Jakarta"]},
    { groupName: "Australia", options: ["Darwin", "Eucla", "Perth", "Brisbane","Lindeman","Adelaide","Hobbart","Currie","Melbourne"]},
  ])

這是選擇選項的代碼。 它將按groupName顯示選項 group。

{{#paper-select options=this.timeZoneOptions
        selected=this.timeZone
        onChange=(action (mut this.timeZone)) as |timeZon| }}
        {{timeZon}}
      {{/paper-select}}

我無法使用{{this.timeZone.groupName}}獲取數據。

如果我想根據用戶選擇的選項獲取groupName我該怎么辦?

你那里的東西似乎是正確的。 也許錯誤在於mut用法,也許它在其他地方。

mut助手非常模糊。 當 Ember 團隊弄清楚如何優雅地做到這一點時,它將被棄用。

您可以通過在控制器/組件上創建不同的操作來避免mut助手。

這將讓您進行調試:只需將debugger語句放入您的操作中並從那里繼續。

經典 Ember 風格:

import Component from '@ember/component';

export default Component.extend({
  timeZoneOptions: Object.freeze([
    { groupName: "Asia", options:["Kabul","Yerevan","Baku","Dhaka","Brunei","Bangkok","Shanghai","Urumqi","Taipei","Macau","Tbilisi","Dili","Kolkata","Jakarta"]},
    { groupName: "Australia", options: ["Darwin", "Eucla", "Perth", "Brisbane","Lindeman","Adelaide","Hobbart","Currie","Melbourne"]},
  ]),

  currentTimeZoneOption: null,

  actions: {
    selectTimeZoneOption(timeZoneOption) {
      this.set('currentTimeZoneOption', timeZoneOption');
    }
  }
});
{{#paper-select
  options=this.timeZoneOptions
  selected=this.currentTimeZoneOption
  onChange=(action 'selectTimeZoneOption')
  as |timeZoneOption|
}}
  {{timeZoneOption}}
{{/paper-select}}

<p>
  Current timezone option:
  {{this.currentTimeZoneOption.groupName}}
</p>

Ember Octane 風格:

import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';

export default class MyComponent extends Component {
  timeZoneOptions = Object.freeze([
    { groupName: "Asia", options:["Kabul","Yerevan","Baku","Dhaka","Brunei","Bangkok","Shanghai","Urumqi","Taipei","Macau","Tbilisi","Dili","Kolkata","Jakarta"]},
    { groupName: "Australia", options: ["Darwin", "Eucla", "Perth", "Brisbane","Lindeman","Adelaide","Hobbart","Currie","Melbourne"]},
  ]);

  @tracked
  currentTimeZoneOption = null;

  @action
  selectTimeZoneOption(timeZoneOption) {
    this.currentTimeZoneOption = timeZoneOption;
  }
}
<div class="my-component">
  <PaperSelect
    @options={{this.timeZoneOptions}}
    @selected={{this.currentTimeZoneOption}}
    @onChange={{this.selectTimeZoneOption}}
    as |timeZoneOption|
  >
    {{timeZoneOption}}
  </PaperSelect>

  <p>
    Current timezone option:
    {{this.currentTimeZoneOption.groupName}}
  </p>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM