vue3:使用插件递归组件
- 首先安装插件
npm i unplugin-vue-define-options
- vite.config.ts 配置插件
// vite.config.ts
// 引入 unplugin-vue-define-options
import DefineOptions from "unplugin-vue-define-options";
export default defineConfig({
// 注册插件 DefineOptions
plugins: [DefineOptions(),vue()],
css:{
preprocessorOptions:{
scss:{
// 全局引入scss
additionalData:`@import "./src/bem.scss";`
}
}
}
})
- tsconfig.json 配置插件
{
"compilerOptions": {
// 配置插件 DefineOptions
"types": [ "unplugin-vue-define-options/macros-global" ]
}
}
- 新建Tree.vue组件
<template>
<div class="tree" v-for="item in data">
<input v-model="item.checked" type="checkbox"> <span>{{ item.name }}</span>
<!-- 递归组件 -->
<xiaotian v-if="item?.children?.length" :data="item?.children"></xiaotian>
</div>
</template>
<script setup lang='ts'>
import { ref, reactive} from 'vue'
interface Tree {
name:string,
checked: boolean,
children?: Tree[]
}
// 递归组件名称,可以看作是当前组件的name名称
defineOptions({
name:"xiaotian"
})
defineProps<{
data?:Tree
}>()
</script>
<style scoped lang="less">
.tree{
margin-left: 10px;
}
</style>
- 引入tree.vue组件
<template>
<div>
<TreeVue :data="data"></TreeVue>
</div>
</template>
<script setup lang='ts'>
import { ref, reactive } from 'vue';
import TreeVue from "./components/Tree.vue";
interface Tree {
name:string,
checked: boolean,
children?: Tree[]
}
const data = reactive<Tree[]>([
{
name:"1",
checked:false,
children:[
{
name:"1-1",
checked:false
}
]
},
{
name:"2",
checked:false
},
{
name:"3",
checked:false,
children:[
{
name:"3-1",
checked:false,
children:[
{
name:"3-1-1",
checked:false
},
{
name:"3-1-2",
checked:false
}
]
}
]
}
])
</script>
<style lang="less">
</style>
后台向作者提问