LoginSignup
18
13

More than 1 year has passed since last update.

Vue3 の Composition API で親コンポーネントから子コンポーネントのメソッドを呼び出す(逆も)

Last updated at Posted at 2022-12-05

主旨

App.vue から childComponent.vue のメソッドを呼び出す例です。ボタンを押したときに、数字が1ずつ増加すれば成功です。

<script setup> を使う場合で、親側を呼び出すサンプルはたくさん見つかるのに、子側を呼び出す例が見つけられなかったので、ここにメモしておきます。

defineExpose() を使うところが分からなかった。

参考

親から子メソッドを呼び出す

親側

/src/App.vue
<script setup>
import {ref} from 'vue';

// 子のメソッド呼び出しに必要な部分
import ChildComponent from './components/childComponent.vue';
const childComponent = ref();

function increment(){
  childComponent.value.incrementNumber();
}
// 子のメソッド呼び出しに必要な部分(ここまで)
</script>

<template>
  <ChildComponent ref="childComponent"></ChildComponent>
  <button @click="increment">Increment</button>
</template>

子側

/src/components/childComponent.vue
<script setup>
import {ref} from 'vue';

// このファイル (childComponent.vue) は
// /src/components/ 以下にあるものとする

// 親からの呼び出しに必要な部分
const number = ref(0);
function incrementNumber()
{
  number.value++;
}

defineExpose({
  incrementNumber,
});
// 親からの呼び出しに必要な部分 (ここまで)

</script>
<template>
  <div>
    Child: {{ number }}
  </div>
</template>

子から親メソッドを呼び出す

親側

/src/App.vue
<script setup>
import {ref} from 'vue';

// 子からの呼び出しに必要な部分
import ChildComponentSecond from './components/childComponentSecond.vue';

const number = ref(0);

function incrementParent(){
  number.value ++;  
}
// 子からの呼び出しに必要な部分(ここまで)
</script>

<template>
  <div>
    Parent: {{ number }}
    <ChildComponentSecond @click="incrementParent">
    </ChildComponentSecond>
  </div>
</template>

子側

/src/components/childComponentSecond.vue
<script setup>

// 親の呼び出しに必要な部分
const emit = defineEmits(['incremetParent']);
// 親の呼び出しに必要な部分 (ここまで)

</script>

<template>
  <div>
    <button @click="emit('incremetParent')">
      Increment
    </button>
  </div>
</template>

おまけ(props)

親側

/src/App.vue
<script setup>
import {ref} from 'vue';
import ChildComponentThird from './components/childComponentThird.vue';
const parentNumber = ref(100);
</script>

<template>
  <div>
    <ChildComponentThird
      :childNumber="parentNumber"
    ></ChildComponentThird>
  </div>
</template>

子側

/src/components/ChildComponentThird.vue
<template>
  <div>
    <p>ChildNumber: {{ childNumber }}</p>
  </div>
</template>

<script setup>
const props = withDefaults(defineProps(),{
  childNumber: 0,
});
</script>

Typescript 版もそのうち書いときます(100年以内)

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