1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vue3 defineExpose()が上手くいかないので回避策を入れた

Posted at

Vue3始めました

今までVue2使っていましたが、最近手を付け始めたプロジェクトからVue3への移行をすることにした。
早速ハマった問題が。

Vue3 defineExpose()が上手くいかない

Vue3では、親コンポーネントから子コンポーネントの関数呼び出しは、
子コンポーネント上にdefineExpose([xxx])で宣言して、DOMにrefをつけて参照すると、
ref.value.xxx()で呼べる。
みたいなこと書いてあるんだけど
自分の環境(3.4.9)で上手くいかない
ref.valueの下にdefineExposeの宣言したものが生えてこない。

見えないところには、ちゃんと生えているので
それを使った回避策
defineExpose([])の中身が
ref.value.$.exposed
にそのまま配列で入っているのでそれを呼ぶ。

<script setup lang="ts">
import ComponentA from "componentA.vue";

const compA = ref(null);
const callChildComponentEvent = (component:any,arg:unknown) => {
  if(component && component.value && component.value.$ && Array.isArray(component.value.$.exposed)){
    if(typeof component.value.$.exposed[0] === "function"){
      component.value.$.exposed[0](arg);
      return true;
    }
  }
  return false;
}
const onFire = () =>{
  callChildComponentEvent(compA,"Fire!");
}
</script>
<template>
    <ComponentA ref="compA"></ComponentA>
    <button :onclick="onFire">Fire</button>
</template>

<script setup lang="ts">

const evetCall = (arg:unknown) => {
    console.log(arg);
}
defineExpose([evetCall]);//0に呼ぶ関数を入れておく
</script>
<template>
</template>
Console
Fire!

そもそもの原因

これ、関係しているような気もするけど、はっきりわかっていない。

なんか、別の問題が起きているかもしれない。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?