在前端开发中,vue.js 是一个流行的 javascript 框架,它能够使我们开发复杂的单页面应用变得更加简单。vue.js 通过数据驱动视图的方式来实现单向数据流。在开发过程中,我们经常需要用到表格来展示数据。vue.js 提供了一些常用的表格组件,但如果我们需要在一个页面上面展示多个表格,该怎么做呢?本文将详细介绍如何在一个页面中展示多个表格。
1. 使用两个组件实现两个表格vue.js 中的组件是一个独立的单元,它的行为和数据可以在不同的上下文中使用。考虑到组件每次都会重新渲染,我们可以使用两个组件来实现不同的表格展示。
首先,我们创建两个组件,“table1”和“table2”:
<template> <table> <thead> <tr> <th>id</th> <th>name</th> <th>age</th> </tr> </thead> <tbody> <tr v-for="item in data" :key="item.id"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.age}}</td> </tr> </tbody> </table></template><script>export default { props: { data: array }}</script>
这里,我们创建两个表格组件,并且使用互不干扰的 props 来传递数据。在父组件中,我们将数据分别传递给这两个组件,用 v-bind 指令实现:
<template> <div> <table1 :data="data1"></table1> <table2 :data="data2"></table2> </div></template><script>import table1 from 'path/to/table1.vue'import table2 from 'path/to/table2.vue'export default { components: { table1, table2 }, data() { return { data1: [...], data2: [...] } }}</script>
这样,就可以在同一个页面上显示两个表格了。
2. 使用一个组件实现多个表格在上面的方法中,我们需要创建多个组件,如果需要增加更多的表格,我们需要不断地创建组件。因此,我们可以通过修改组件的 props 来实现在同一个页面上显示多个表格。
我们来修改 table 组件:
<template> <table> <thead> <tr> <th>id</th> <th>name</th> <th>age</th> </tr> </thead> <tbody> <tr v-for="item in data" :key="item.id"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.age}}</td> </tr> </tbody> </table></template><script>export default { props: { data: array, tableid: string }}</script>
在组件中增加了一个新的 prop,用来区分不同的表格。现在我们可以在父组件中使用同一个 table 组件,但是需要给每个表格传递不同的 prop:
<template> <div> <table :data="data1" tableid="table1"></table> <table :data="data2" tableid="table2"></table> </div></template><script>import table from 'path/to/table.vue'export default { components: { table }, data() { return { data1: [...], data2: [...] } }}</script>
在表格中,我们可以根据不同的 tableid 来渲染不同的数据:
<template> <table> <thead> <tr> <th>id</th> <th>name</th> <th>age</th> </tr> </thead> <tbody> <tr v-for="item in filtereddata" :key="item.id"> <td>{{item.id}}</td> <td>{{item.name}}</td> <td>{{item.age}}</td> </tr> </tbody> </table></template><script>export default { props: { data: array, tableid: string }, computed: { filtereddata() { return this.data.filter(item => { return item.tableid === this.tableid }) } }}</script>
这样,我们就可以通过一个 table 组件来展示多个表格了。
综上所述,我们可以使用两个组件实现多个表格,也可以使用一个组件来展示多个表格。前者需要创建多个组件,后者则需要在组件中增加额外的 prop 来使用。根据项目的需求,我们可以选择合适的方法来展示数据。
以上就是vue如何在一个页面中展示多个表格的详细内容。