実現したいこと
親要素にてvfor内の:refを使用して子要素のdefineExposeで定義した関数にアクセスしたい
前提
js
1"vue": "^3.2.13",
下記のようなサイトを作成
- hello world コンポーネントを作成してそれをv-forで表示
- さらにそのコンポーネントを:refにて取得した
- fireを押下するとdefineExposeで定義した子要素のexposeFunctionを発火させたい
発生している問題・エラーメッセージ
Fire 押下時:refで取得したコンポーネントからexposeFunction
ts
1Uncaught TypeError: componentRef.exposeFunction is not a function2 at eval (HomeView.vue?71c7:27:1)3 at Proxy.forEach (<anonymous>)4 at onFire (HomeView.vue?71c7:26:1)5 at callWithErrorHandling (runtime-core.esm-bundler.js?d2dd:173:1)6 at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?d2dd:182:1)7 at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js?2725:345:1)
該当のソースコード
子要素 HelloWorld.vue
ts
1<template>2 <div class="hello">3 <h1>{{ msg }}</h1>4 </div>5</template>6 7<script setup lang="ts">8import { defineProps, defineExpose } from "vue";9 10interface Props {11 msg: string;12}13const props = defineProps<Props>();14 15function exposeFunction() {16 console.log(props.msg);17}18defineExpose({19 exposeFunction,20});21</script>22 23<!-- Add "scoped" attribute to limit CSS to this component only -->24<style scoped lang="scss"></style>25
親要素 HomeView.vue
ts
1<template>2 <div 3 class="home"4 v-for="item of items"5 :key="item.id"6 :ref="setComponentRefs"7 >8 <HelloWorld :msg="item.value" ref="componentRef" />9 </div>10 <button @click="onFire">Fire</button>11</template>12 13<script setup lang="ts">14import { ref } from "vue";15import HelloWorld from "@/components/HelloWorld.vue"; // @ is an alias to /src16 17const componentRefs = ref<Array<InstanceType<typeof HelloWorld>>>([]);18 19const items = ref([20 { id: "001", value: "vue1" },21 { id: "002", value: "vue2" },22 { id: "003", value: "vue3" },23]);24// eslint-disable-next-line @typescript-eslint/no-explicit-any25function setComponentRefs(el: any) {26 if (el) {27 componentRefs.value.push(el as InstanceType<typeof HelloWorld>);28 }29}30function onFire() {31 componentRefs.value.forEach((componentRef) => {32 componentRef.exposeFunction();33 });34}35</script>36
ちなみにvscodeのホバーした際のヒントでは正常に出てくる(型定義が影響しているかも?)
試したこと
v-forを使用せずに単体コンポーネントのリファレンスのexploreFunctionは正常に発火する
補足情報(FW/ツールのバージョンなど)
該当ソースコードをアップしましたので、再現などにお役立てください
https://github.com/mendakon/defineEmitnotWorked

0 コメント