我正在Vuejs
应用程序中构建一个通用表组件,如下所示:
表组件:
<template>
<div>
<table class="table">
<thead>
<tr>
<th v-for="item in headers">
{{ item }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in contents">
<th scope="row">
{{ index+1 }}
</th>
<td>
{{ item.first_name }}
</td>
<td>
{{ item.last_name }}
</td>
<td>
{{ item.username }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
name: "table-type-1",
props: ['contents', 'headers']
}
</script>
如果我通过道具中的以下数据集,这将起作用:
data() {
return {
headers: ['#', 'First Name', 'Last Name', 'Username'],
contents: [
{ first_name: 'Jhon', last_name: 'Stone', username: '@jhon' },
{ first_name: 'Lisa', last_name: 'Nilson', username: '@lisa' },
{ first_name: 'Larry', last_name: 'the Bird', username: '@twitter' }
]
}
}
但是由于我要建立一个公用表,所以我的数据集可以不同,所以有时可能是这样的:
data() {
return {
headers: ['#', 'Company Name', 'City', 'Turn Over (In Billions)'],
contents: [
{ company_name: 'ABC Infotech', city: 'New Jersey', turn_over: 100 },
{ company_name: 'Amazon Web Services', city: 'New York', turn_over: 400 },
{ company_name: 'Digital Ocean', city: 'Washington', turn_over: 200 }
]
}
}
或者可以是不同的结构。为此,我正在考虑在标头数据中传递键值集,该值可以确定将哪些键表示给哪一列,如下所示:
data() {
return {
headers: [
{ title: '#', key: index, },
{ title: 'Company Name', key: 'company_name'},
{ title: 'City', key: 'city'},
{ title: 'Turn Over (In Billions)', key: 'turn_over' }
],
contents: [
{ company_name: 'ABC Infotech', city: 'New Jersey', turn_over: 100 },
{ company_name: 'Amazon Web Services', city: 'New York', turn_over: 400 },
{ company_name: 'Digital Ocean', city: 'Washington', turn_over: 200 }
]
}
}
或者只是传递键变量:
data() {
return {
headers: ['#', 'Company Name', 'City', 'Turn Over (In Billions)'],
keys: ['index', 'company_name', 'city', 'turn_over'],
contents: [
{ company_name: 'ABC Infotech', city: 'New Jersey', turn_over: 100 },
{ company_name: 'Amazon Web Services', city: 'New York', turn_over: 400 },
{ company_name: 'Digital Ocean', city: 'Washington', turn_over: 200 }
]
}
}
如何实现?或者可以通过这种方法将这些键放在v-for元素中?欢迎任何建议。谢谢。
答案 0 :(得分:2)
对于通过标题的每一行循环,提取get_the_ID();
并通过key
获得内容:
key
new Vue({
el: '#app',
data: {
headers: [
{ title: '#', key: 'index' },
{ title: 'Company Name', key: 'company_name'},
{ title: 'City', key: 'city'},
{ title: 'Turn Over (In Billions)', key: 'turn_over' }
],
contents: [
{ company_name: 'ABC Infotech', city: 'New Jersey', turn_over: 100 },
{ company_name: 'Amazon Web Services', city: 'New York', turn_over: 400 },
{ company_name: 'Digital Ocean', city: 'Washington', turn_over: 200 }
]
}
})