简体   繁体   English

如何使用计算属性和道具过滤对象 [VueJS]

[英]How to filter an object using computed property and props [VueJS]

Firstly, thanks in advance for reading and helping out.首先,提前感谢您的阅读和帮助。

I am a bit lost trying to solve this.试图解决这个问题我有点迷茫。 I currently have two Dropdown components which renders different options from an object.我目前有两个 Dropdown 组件,它们从一个对象呈现不同的选项。 Im rendering two dropdowns.我渲染了两个下拉菜单。 The second dropdown will depend on the selection of the first dropdown.第二个下拉列表将取决于第一个下拉列表的选择。

Let's say I select "BMW" in the first dropdown, and it should only render "BMW 320i".假设我在第一个下拉列表中选择了“BMW”,它应该只呈现“BMW 320i”。

The data object looks like this:数据对象如下所示:

{
   "menu":[
      {
         "id":"bmw",
         "name":"BMW"
      },
      {
         "id":"volvo",
         "name":"Volvo"
      }
   ],
   "cars":[
      {
         "id":"bmw320",
         "name":"BMW 320i"
      },
      {
         "id":"volvoc70",
         "name":"Volvo C70"
      }
   ]
}

In my template I have two child components which include the dropdown.在我的模板中,我有两个包含下拉列表的子组件。 The MenuDropdown includes the dataContent.menu content, and CarDropdown includes dataContent.cars content. MenuDropdown包括dataContent.menu内容, CarDropdown包括dataContent.cars内容。

<MenuDropdown :dataContent="dataContent">
<CarDropdown :dataContent="customDataContent">

The options of the CarDropdown will change depending on the selection of the first dropdown (MenuDropdown). CarDropdown 的选项将根据第一个下拉列表 (MenuDropdown) 的选择而变化。 So I am trying to achieve this by using a computed property:所以我试图通过使用计算属性来实现这一点:

computed: {
    customDataContent() {
        if (this.dataContent.menu.id === "bmw") {
            return this.dataContent.cars.filter(car => {
                return car.id === 'bmw320'
            })
        } else {
            return this.dataContent
        }
    }
}

Thanks for the help!谢谢您的帮助!

the filter method returns an array, index it with [0] or use Array.find() instead filter方法返回一个数组,用[0]索引它或使用 Array.find() 代替

With find随着发现

return this.dataContent.cars.find(car => car.id === 'bmw320')

With filter带过滤器

return this.dataContent.cars.filter(car => car.id === 'bmw320')[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM