前端页面打开自动请求并加载出数据库数据表内容 已知axios封装好的接口为list 来自文件夹api 的AppData.js 在vue3在使用<script setup> 组合式写法
时间: 2024-03-05 08:50:27 浏览: 20
在 Vue 3 中,你可以使用组合式 API 的 `setup` 函数来请求并加载数据库数据表内容。下面是一个示例代码:
```html
<template>
<div>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { list } from '@/api/AppData'
export default {
setup() {
const items = ref([])
onMounted(async () => {
try {
const res = await list()
items.value = res.data
} catch (error) {
console.error(error)
}
})
return {
items
}
}
}
</script>
```
在这个示例中,我们使用 `ref` 创建了一个响应式的 `items` 变量来存储数据库数据表内容。在 `onMounted` 钩子函数中,我们使用 `list` 函数来获取数据,并将其赋值给 `items` 变量。最后,我们将 `items` 变量暴露出去,以便在模板中使用。
注意,`list` 函数应该返回一个 Promise 对象,它的 `data` 属性包含了数据库数据表内容。另外,我们还需要在 `import` 语句中引入 `list` 函数,这里假设它已经在 `api/AppData.js` 文件中定义好了。