JavaScript/vue.js/ref

来自康健生活
跳转到导航 跳转到搜索

引言

  • 在普通的元素上,this.ref.name 获取到的是 dom 元素
  • 在子组件上,this.ref.name 获取到的是组件实例,可以使用组件的所有方法

引用 DOM

组件内 DOM

<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>

组件

<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>

函数

<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>

动态

<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>