使用vue3+ts写一个表格,表格中数据需要请求/admin/query接口获取,获取到数据后将其渲染到表格中
时间: 2024-02-06 19:10:10 浏览: 24
首先,需要安装 `axios` 模块来进行网络请求。可以在终端中执行以下命令进行安装:
```bash
npm install axios --save
```
接下来,在 Vue 组件中引入 `axios` 模块,并编写获取数据的方法:
```typescript
import { defineComponent } from 'vue'
import axios from 'axios'
interface DataItem {
id: number
name: string
age: number
}
export default defineComponent({
data() {
return {
data: [] as DataItem[],
}
},
mounted() {
this.getData()
},
methods: {
async getData() {
try {
const response = await axios.get('/admin/query')
this.data = response.data
} catch (error) {
console.error(error)
}
},
},
})
```
以上代码中,我们定义了一个 `DataItem` 接口来表示数据项的类型。在组件中,我们使用 `axios.get` 方法来获取数据,并将获取到的数据保存在组件的 `data` 属性中。
接下来,我们需要在模板中渲染表格。可以使用 `v-for` 指令来遍历数据,并使用 `v-bind` 指令将数据绑定到表格中的每一行:
```html
<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>
```
最后,我们需要在 Vue 组件中注册接口的地址 `/admin/query`。可以在 `main.ts` 中使用 `createApp` 函数的 `provide` 方法来注册全局变量:
```typescript
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
const app = createApp(App)
app.provide('API_URL', '/admin/query')
app.mount('#app')
```
现在,我们已经完成了一个简单的表格组件,并且可以从接口中获取数据并渲染表格。完整代码如下:
```typescript
<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 lang="ts">
import { defineComponent, inject } from 'vue'
import axios from 'axios'
interface DataItem {
id: number
name: string
age: number
}
export default defineComponent({
data() {
return {
data: [] as DataItem[],
}
},
mounted() {
this.getData()
},
methods: {
async getData() {
try {
const apiUrl = inject<string>('API_URL')
const response = await axios.get(apiUrl)
this.data = response.data
} catch (error) {
console.error(error)
}
},
},
})
</script>
```