【问题标题】:Parsing objects as props while looping through them in child component VueJS在子组件VueJS中循环遍历对象时将对象解析为道具
【发布时间】:2021-08-27 05:13:50
【问题描述】:

我有一个表组件,我想让它可重复使用。 Table 组件接收一个对象数组,并使用 v-for 指令循环遍历它们。 Table 组件如下所示:

<template>
    <table>

      <thead>
       <tr>
        <th v-for="header in tableHeaders">{{ header }}</th>
       </tr>
      </thead>

      <tbody>
       <tr v-for="elements in tableData">
        <td>{{ elements }}</td>
       </tr>
      </tbody>

    </table>
</template>

<script>

export default {
  name: "Table",
  props: {
    tableData: Array,
    tableHeaders: Array,
    header: String
  },
}
</script>

然后我想在父组件中重用这个,解析tableData是一个对象数组。这工作正常,但我找不到访问属性的方法。相反,我在每个 td 元素中获得了整个对象。父组件如下所示:

<template>
    <Table title="All users in the community" :table-data="users" :table-headers="headers"/> 
</template>


<script>
import Table from "@/components/Table";

export default {
  components: {
    Table
  },
  data() {
    return {
      users: [{name: "firstName", email: "firstEmail"}, {name: "secoundName", email: "secoundEmail"}], 
      headers: ["Name", "Email"],
    };
  },
};
</script>

我尝试以不同的方式绑定它,并且现在知道“元素”绑定,原因是解析整个对象。

所以我的问题是,如何访问父组件中的 users.name?我对 VueJS 还是有点陌生​​。提前谢谢你。

【问题讨论】:

    标签: javascript vue.js parsing components vue-props


    【解决方案1】:

    您可以将属性名称作为键传递到标题中,然后根据该键映射您的元素:

    headers: [{label:"Name",key:"name"},{label: "Email",key:"email"}],
    

    表格组件:

       <table>
    
          <thead>
           <tr>
            <th v-for="header in tableHeaders">{{ header.label }}</th>
           </tr>
          </thead>
    
          <tbody>
           <tr v-for="elements in tableData">
            <td v-for="header in tableHeaders">{{elements[header.key]}}</td>
           </tr>
          </tbody>
    
        </table>
    

    【讨论】:

    • 谢谢你!正是我想要的。
    【解决方案2】:

    您可以在父组件中使用计算属性,例如对于用户:

    computed: {
      tableUsers() {
        return this.users.map(user => user.name);
      }
    }
    

    然后在组件的 props 中使用它:

    <Table title="All users in the community" :table-data="tableUsers" :table-headers="headers"/> 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      相关资源
      最近更新 更多