vue实现表格读取数据
Vue 实现表格读取数据的方法
使用静态数据
静态数据可以直接在 Vue 组件的 data 中定义,并通过 v-for 指令渲染到表格中。
<template>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
]
}
}
}
</script>
从 API 获取动态数据
通过 axios 或 fetch 从后端 API 获取数据,并在 created 或 mounted 钩子中调用。
<template>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
tableData: []
}
},
async created() {
try {
const response = await axios.get('https://api.example.com/users');
this.tableData = response.data;
} catch (error) {
console.error('Error fetching data:', error);
}
}
}
</script>
使用计算属性处理数据
如果需要处理数据后再显示,可以使用计算属性。
<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 {
data() {
return {
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
]
}
},
computed: {
filteredData() {
return this.tableData.filter(item => item.age > 28);
}
}
}
</script>
使用第三方表格组件
如果需要更复杂的表格功能(如排序、分页),可以使用第三方库如 Element UI 或 Vuetify。
<template>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="id" label="ID" width="180"></el-table-column>
<el-table-column prop="name" label="Name" width="180"></el-table-column>
<el-table-column prop="age" label="Age"></el-table-column>
</el-table>
</template>
<script>
export default {
data() {
return {
tableData: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
]
}
}
}
</script>
以上方法涵盖了从静态数据到动态 API 数据的表格实现,以及使用计算属性和第三方库的进阶用法。根据需求选择合适的方式即可。







