显示带有 id 的数组中的特定数据

Display specific data from array with id

我想像这个例子一样显示来自 Vuex 存储数组的数据,

<template>
    <div>
        <h1>{{this.$store.state.data.title}}</h1>
        <p>{{this.$store.state.data.text}}</p>
    </div>
</template>

但是有一个 id 指定我将从数组中的哪个项目中获取它。

是否可行或有其他选择?

您可以使用 computed 属性 :

 <template>
     <div>
        <h1>{{getTitle}}</h1>
        <p>{{getText}}</p>
     </div>
   </template>
<script>
export default {
    computed:{
        getTitle(){
            return this.$store.state.data.find(item => item.id === YOUR_ID).title
        },
        getText(){
            return this.$store.state.data.find(item => item.id === YOUR_ID).text
        }
    }
}
</script>

您可以使用 js 过滤器和 vue.js 计算的 属性 来过滤 table 并根据 id 仅获取您想要的特定值。这是一个例子:

 <template>
     <div>
        <h1>{{mydata.data_title}}</h1>
        <p>{{mydata.data_description}}</p>
     </div>
   </template>
<script>
export default {
    computed:{
        mydata(){
            return {
             data_title: this.$store.state.data.filter(x=> x.id === 1).title,
             data_description: this.$store.state.data.filter(x=> x.id === 1).text
            }
        },
    }
}
</script>