我有一个表组件,我想让它可重用。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的新手。提前谢谢。
您可以将属性名称作为键传递到标头中,然后根据该键映射元素:
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>
您可以在父组件中使用计算属性,例如,对于Users:
computed: {
tableUsers() {
return this.users.map(user => user.name);
}
}
然后在你的组件道具中使用它:
<Table title="All users in the community" :table-data="tableUsers" :table-headers="headers"/>