LoginSignup
1
0

More than 1 year has passed since last update.

【vue3】script setupで親コンポーネントから子コンポーネントにFunctionをpropsとして受け渡す

Posted at

やりたいこと

  • <script setup>で親コンポーネントから子コンポーネントにFunctionをpropsとして受け渡す
    仕事で<script setup>を勉強することがあったのでメモ。
    今回はボタンコンポーネントに親からFunctionを渡しています。

実装

子コンポーネント

<template>
  <div class="button-component">
    <button @click="onClick">{{ label }}</button>
  </div>
</template>

<script setup lang="ts">
import { defineProps } from 'vue';

defineProps({
  label: {
    type: String,
    default: "label"
  },
  onClick: {
    type: Function,
    default: () => {
      console.log("button default")
    }
  }
})
</script>

親コンポーネント

<template>
  <div class="parent">
    <h1>Test Page</h1>
    <button-component label="parent method" @click="onClick"></button-component>
  </div>
</template>

<script setup lang="ts">
import ButtonComponent from '@/components/ButtonComponent.vue';

function onClick () {
  console.log("parent method")
}
</script>

ボタン押してみた

1.PNG

@clickを指定していない方のボタンをクリック
2.PNG
Functionを渡してないのでdefualtのメソッドが呼び出される

@clickを指定した方のボタンをクリック
3.PNG
親から渡したFunctionが実行される

感想

<script setup>はまだまだ慣れないですね。
使いこなせたら便利そう。

1
0
1

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