请给出使用Vue3和ts以树形表格读取后端数据的完整代码
时间: 2024-09-14 16:10:45 浏览: 49
在Vue3中,我们可以使用Vuex来管理数据,配合axios获取后端数据,然后展示在一个树状表格里。下面是一个简单的例子,包括数据获取、Vuex存储以及动态渲染树形结构:
**1. 安装必要的依赖**
```sh
npm install axios vuex typescript axios v-model-loading
```
**2. 配置Vuex store**
```javascript
// src/store/index.ts
import { createStore } from "vuex";
import axios from "axios";
const store = createStore({
state: {
treeData: [],
loading: true,
error: null,
},
mutations: {
SET_TREE_DATA(state, data) {
state.treeData = data;
state.loading = false;
},
SET_LOADING(state, loading) {
state.loading = loading;
},
SET_ERROR(state, error) {
state.error = error;
},
},
actions: {
fetchData({ commit }) {
commit("SET_LOADING", true);
axios.get("/api/tree-data")
.then((response) => {
commit("SET_TREE_DATA", response.data);
})
.catch((error) => {
commit("SET_ERROR", error.message);
});
},
},
});
export default store;
```
**3. 主要组件模板 (例如App.vue)**
```html
<template>
<v-app>
<v-container>
<v-row justify="center" align="top">
<v-loading :active="$store.state.loading" spinner>
<v-data-treeview :items="treeData" :key-as="id" />
</v-loading>
<div v-if="$store.state.error">
<span>Error: {{ $store.state.error }}</span>
</div>
</v-row>
</v-container>
</v-app>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { useStore } from '@/store';
import VDataTreeview from 'v-data-treeview';
const store = useStore();
let treeData = ref([]);
onMounted(() => {
store.dispatch('fetchData');
});
</script>
```
**4. 树节点模型(假设后端返回的是类似这种的数据结构)**
```json
{
id: "1",
name: "根节点",
children: [
{
id: "2",
name: "子节点1"
// 更深一层的子节点...
}
]
}
```
阅读全文