Senar的个人网站 » 首页

vue3中的种种1970-01-01 00:00

Vue3中的种种

props TS

如何声明定义当前组件的props

使用defineProps

interface PropsInterface { num?: number str?: string list: string[] isShow?: boolean } const props = defineProps<PropsInterface>()

当父组件没有某些props,如何设置props的默认值?

使用 withDefaults 编译器宏

const props = withDefault(defineProps<PropsInterface>(), { num: 369, str: 'string', isShow: false })

emits TS

const emit = defineEmits<{ (e: 'change', id: number): void (e: 'update', value: string): void }>()

teleport

如果是传送到vue组件树内部一定要保证要传送到的位置已经存在,常见的做法是使用v-if来保证mounted之后展示要传送的组件

// target A.vue <template> <div id="target-dom"></div> </template> // B.vue <script setup> const showTeleport = ref(false) onMounted(() => showTeleport.value = true) </script> <template> <teleport v-if="showTeleport" to="#target-dom"> <span>I'm from B.vue</span> </teleport> <div> <button></button> </div> </template>

ref

要想拿到ref引用的节点,需要在节点已经挂载之后。

单节点ref

需要声明一个变量引用到模板里面的节点

<script setup lang="ts"> const imgRef = ref<HTMLImageElement>(null) </script> <template> <img src="xxx" ref="imgRef" /> </template>

v-for上的多节点ref

需要引用一个方法将节点便利到一个数组中

<script setup lang="ts"> const urls = ['xxx', 'xxx'] const imgsRef = ref<HTMLImageElement[]>([]) function setImgsRef(el: HTMLImageElement){ imgsRef.value.push(el) } </script> <template> <img v-for="(url) in urls" :key="url" :src="url" :ref="setImgsRef" /> </template>