【问题标题】:Vuejs how to use computed properties with a forEach loopVuejs 如何在 forEach 循环中使用计算属性
【发布时间】:2018-08-13 17:13:32
【问题描述】:

我的用例是这样的,

  1. 我循环遍历一组对象以填充下拉菜单。
  2. 如果我使用 v-model 下拉列表,我只能获取对象 ID 或名称。但我可以同时获得 id 和 name。
  3. 所以我需要计算属性来查找所选对象的 id。

这是我的 v-select

<v-select
                label="Select an item"
                :items="items"
                item-text="name"
                v-model="item_name">
                </v-select>

这是我的计算属性

 computed: {
        id() {
          this.items.forEach(element => {
            if (element.name == this.item_name) {
              return (this.item = element.id);
            }
          });
        }

  }

我希望 {{item}} 打印所选项目的 id 的计算属性出了什么问题,但它没有。

【问题讨论】:

  • 尝试:返回 this.item.forEach()...

标签: vue.js vuejs2


【解决方案1】:

您可以改用find()

computed: {
        id() {
          return this.items.find(element => {
            return element.name == this.item.name
          }).id;
        }

  }

这将首先在Array中找到与函数中的条件匹配的元素,然后是该元素的id

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 2019-05-19
    • 2019-11-22
    • 2019-03-01
    • 2019-03-21
    • 2019-05-14
    • 2019-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多