JavaScript/vue.js/ref:修订间差异
来自康健生活
| (未显示同一用户的4个中间版本) | |||
| 第30行: | 第30行: | ||
import ChildComponent from './ChildComponent.vue'; | import ChildComponent from './ChildComponent.vue'; | ||
... | ... | ||
// 类型推断 InstanceType<T> | |||
const comp = ref<InstanceType<typeof ChildComponent> | null>(null); | const comp = ref<InstanceType<typeof ChildComponent> | null>(null); | ||
onMounted(() => { | onMounted(() => { | ||
| 第36行: | 第37行: | ||
... | ... | ||
</script></syntaxhighlight> | </script></syntaxhighlight> | ||
== 函数 == | |||
<syntaxhighlight lang="html5"> | |||
<template> | |||
<div ref="update">Hello, Vue 3 with TypeScript!</div> | |||
</template> | |||
<script lang="ts" setup> | |||
import { ref, ComponentPublicInstance, HTMLAttributes } from 'vue'; | |||
... | |||
const update = (el: HTMLElement | ComponentPublicInstance | HTMLAttributes) => { | |||
console.log(el); | |||
}; | |||
... | |||
</script></syntaxhighlight> | |||
== 动态 == | |||
<syntaxhighlight lang="html5"> | |||
<div | |||
class="drag first-of-type:mt-(--p-gap) last-of-type:mb-(--p-gap)" | |||
v-for="(param, index) in paramList" | |||
:ref="(el: TRefItem) => setRefMap(el, param)" | |||
:key="param.id" | |||
> | |||
<KeyValueModule | |||
v-model:name="param.key" | |||
/> | |||
</div> | |||
<script setup> | |||
... | |||
type TRefItem = Element | ComponentPublicInstance | null | |||
type TRefItemMap = Record<string, TRefItem> | |||
const refMap = ref<TRefItemMap>({}) | |||
const setRefMap = (el: TRefItem, item: { id: number }) => { | |||
if (el) { | |||
refMap.value[`${item.id}`] = el | |||
} | |||
} | |||
</script> | |||
</syntaxhighlight> | |||