【问题标题】:get two values of json into <b-form-select> text-field将两个 json 值放入 <b-form-select> 文本字段
【发布时间】:2022-01-01 16:59:08
【问题描述】:

我正在与BootstrapVue 合作。

我有一个具有以下结构的 json:

[
    {"ID": "123", "Name": "Harry", "Age": "22"},
    {"ID": "456", "Name": "Harry", "Age": "18"},
    {"ID": "789", "Name": "Peter", "Age": "20"},
    {"ID": "159", "Name": "Peter", "Age": "19"},
]

因此,至少,为了清楚起见,每个数据 - 基于 NameAge 一起 - 是唯一的,也没有 ID (!)。这只是一个示例,以使其更易于理解。

我现在要做的是在&lt;b-form-select&gt; 中显示Name,并在后面的括号中显示Age。例如:Peter (20)

目前我有以下代码:

<b-form-select :options="sortedPersons" text-field="Name" value-field="ID"></b-form-select>

我需要将value 传递给我的parent.vue,但想在其中显示文本。所以我决定这样做。

我现在唯一需要的就是获得关注。这个例子是为了简单地展示我想要的:

:text-field="'Name' + ' ' + '(' + 'Age' + ')'",但这不起作用。

我怎样才能让它运行?

附加信息 - 我在computed 中运行我的json,然后对其进行排序。

sortedPersons() {
  var array = this.json.map((input) => input);
  return array.sort((a, b) => {
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
  });
},

提前致谢!

【问题讨论】:

    标签: javascript vue.js vuejs2 bootstrap-vue


    【解决方案1】:

    您要么需要映射数据,以便将所需文本格式化为单个属性,要么使用 options 属性删除,而使用 v-for 手动创建 &lt;option&gt; 标记。

    new Vue({
      el: "#app",
      data() {
        return {
          selected: '',
          options: [
              {"ID": "123", "Name": "Harry", "Age": "22"},
              {"ID": "456", "Name": "Harry", "Age": "18"},
              {"ID": "789", "Name": "Peter", "Age": "20"},
              {"ID": "159", "Name": "Peter", "Age": "19"},
          ]
        };
      }
    });
    <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" />
    <script src="//unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
    <script src="//unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.min.js"></script>
    
    
    <div id="app" class="p-4">
      <b-select v-model="selected">
        <option v-for="option in options" :key="option.ID" :value="option.ID">
          {{ option.Name }} ({{ option.Age }})
        </option>
      </b-select>
    
      Selected: {{ selected }}
    </div>

    【讨论】:

    • 仅供大家参考:我使用b-form-select 而不是“仅”b-select,而且效果也很好。所以谢谢你帮助我!
    • &lt;b-select&gt; 只是&lt;b-form-select&gt; 的别名,所以它们是同一个组件。使用别名只是我的一个习惯,因为它更短:)
    猜你喜欢
    • 1970-01-01
    • 2019-05-13
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多