JavaScript/vue.js/ref:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
 
(未显示同一用户的2个中间版本)
第37行: 第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>

2025年7月4日 (五) 14:29的最新版本

引言

  • 在普通的元素上,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>