JavaScript/vue.js/ref:修订间差异
来自康健生活
创建页面,内容为“== 引言 == * 在普通的元素上,this.ref.name 获取到的是 dom 元素 * 在子组件上,this.ref.name 获取到的是组件实例,可以使用组件的…” |
|||
| (未显示同一用户的5个中间版本) | |||
| 第2行: | 第2行: | ||
* 在普通的元素上,this.ref.name 获取到的是 dom 元素 | * 在普通的元素上,this.ref.name 获取到的是 dom 元素 | ||
* 在子组件上,this.ref.name 获取到的是组件实例,可以使用组件的所有方法 | * 在子组件上,this.ref.name 获取到的是组件实例,可以使用组件的所有方法 | ||
== 引用 DOM == | |||
=== 组件内 DOM === | |||
<syntaxhighlight lang="html5"> | |||
<template> | |||
<div ref="dom">Hello, Vue 3 with TypeScript!</div> | |||
</template> | |||
<script lang="ts" setup> | |||
import { ref, onMounted } from 'vue'; | |||
... | |||
const dom = ref<HTMLDivElement | null>(null); | |||
onMounted(() => { | |||
if (dom.value) console.log(dom.value); | |||
}); | |||
... | |||
</script> | |||
</syntaxhighlight> | |||
=== 组件 === | |||
<syntaxhighlight lang="html5"> | |||
<template> | |||
<ChildComponent ref="comp" /> | |||
</template> | |||
<script lang="ts" setup> | |||
import { ref, onMounted, type InstanceType } from 'vue'; | |||
import ChildComponent from './ChildComponent.vue'; | |||
... | |||
// 类型推断 InstanceType<T> | |||
const comp = ref<InstanceType<typeof ChildComponent> | null>(null); | |||
onMounted(() => { | |||
if (comp.value) console.log(comp.value); | |||
}); | |||
... | |||
</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> | |||