其他原创
# 全局注册
# 动态组件
可用于 tab 渲染。
// 伪代码
<template>
<view class="content">
<!-- 使用 component 来实现动态渲染组件 -->
<component :is="current.comName"></component>
<!-- 需要注意的是 is 为动态传递 -->
<!-- 若需传递字符串给 is 则需要注册,在 setup 下的 script 中注册 -->
<!-- <component is="A"></component> -->
</view>
</template>
<script setup lang="ts">
import { reactive, markRaw } from 'vue'
import A from '@/component/A'
import B from '@/component/B'
import C from '@/component/C'
type Tabs = {
name: string,
comName: any
}
// Pick 从 指定类型中,摘取对应对象的类型
type Com = Pick<Tabs, 'comName'>
const data = reactive<Tabs[]>([
{
name: '我是a组件',
comName: A // 可以直接渲染,会 proxy(代理) ,耗性能
}, {
name: '我是b组件',
comName: markRaw(B) // 这样组件不会被 proxy ,提高性能
}, {
name: '我是C组件',
comName: markRaw(C)
}
])
let current = reactive<Com>({
comName: data[0].comName
})
</script>
<script lang="ts">
export default {
components: {
A,
B,
C
}
}
</script>
# 递归
一般用树形,如: 侧边栏菜单。
特别注意,递归调用时,外层时间记得用 stop 不然点击内层组件,会递归调用事件。
<div class="ml-2">
<div @click.stop="clickItem(item)" :key="index" v-for="(item, index) in data">
{{ item.name }}
<!-- 递归调用 本组件 item?.children?.leng 当item 的 children 没有定义 length时,返回 undefine,而不会报错 -->
<!-- item?.children?.leng ?? [] 当item 的 children 没有定义 length时,返回 [] -->
<TreeItem @click.stop="clickItem(items)" v-if="item?.children?.leng" :key="indexs"
v-for="(items, indexs) in item.children"></TreeItem>
</div>
</div>
上次更新: 2022/08/23, 18:12:45