Vue 动态表格 数据获取
时间: 2023-12-22 07:48:56 浏览: 89
Vue动态表格数据获取的方式有多种,具体取决于您的数据来源和需求。以下是几种常见的方式:
1. 通过 Ajax 请求获取数据
您可以使用 Vue 的生命周期钩子函数中的 created() 或 mounted() 方法来发起 Ajax 请求获取数据。例如:
```
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.gender}}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: []
}
},
created() {
this.getTableData()
},
methods: {
getTableData() {
axios.get('/api/tableData').then(res => {
this.tableData = res.data
})
}
}
}
</script>
```
2. 通过 props 接收父组件传递的数据
如果您的表格数据来自于父组件,您可以使用 props 来接收父组件传递的数据。例如:
```
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.gender}}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
props: {
tableData: {
type: Array,
required: true
}
}
}
</script>
```
在父组件中,您可以通过绑定 props 来传递数据。例如:
```
<template>
<div>
<my-table :tableData="tableData"></my-table>
</div>
</template>
<script>
import MyTable from './MyTable'
export default {
components: {
MyTable
},
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 18, gender: '男' },
{ id: 2, name: '李四', age: 20, gender: '女' },
{ id: 3, name: '王五', age: 22, gender: '男' }
]
}
}
}
</script>
```
3. 在组件内部定义数据
如果您的表格数据是静态的,您可以在组件内部定义数据。例如:
```
<template>
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{item.name}}</td>
<td>{{item.age}}</td>
<td>{{item.gender}}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: '张三', age: 18, gender: '男' },
{ id: 2, name: '李四', age: 20, gender: '女' },
{ id: 3, name: '王五', age: 22, gender: '男' }
]
}
}
}
</script>
```
在这种情况下,您可以在组件内部对数据进行操作或过滤,而无需发起 Ajax 请求或向父组件传递数据。
阅读全文
相关推荐















