53
37

More than 3 years have passed since last update.

Vue(Nuxt.js) で親子コンポーネント間でイベント(メソッド)を呼び出す方法

Last updated at Posted at 2020-07-18

Vue(Nuxt.js) で親子コンポーネント間でイベント(メソッド)の呼び出す方法です。

まずは、親コンポーネントで子コンポーネントを読み込む

↓子コンポーネント↓

Child.vue
<template>
  <div class="child">
    <button @click="childEvent">親のイベントを呼び出す</button>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
export default Vue.extend({})
</script>

↓親コンポーネント↓

Parent.vue
<template>
  <div class="parent">
    <Child @parent-event="parentEvent" />
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Child from '~/components/Child.vue'

export default Vue.extend({
  components: {
    Child
  }
})
</script>

子コンポーネントから親コンポーネントのイベント(メソッド)を呼び出す

Child.vue
<template>
  <div class="child">
    <button @click="childEvent">親のイベントを呼び出す</button>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  methods: {
    childEvent() {
      this.$emit('parent-event')
    }
  }
})
</script>

Parent.vue
<template>
  <div class="parent">
    <Child @parent-event="parentEvent" />
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Child from '~/components/Child.vue'

export default Vue.extend({
  components: {
    Child
  },
  methods: {
    parentEvent() {
      console.log('parentEvent')
    }
  }
})
</script>

this.$emit('parent-event')で親にイベントを伝えます。
<Child @parent-event="parentEvent" /> で親は受け取ったイベントで、自身のイベント(メソッド)を呼び出します。

イベントと共に引数を渡すこともできる

Child.vue
this.$emit('parent-event', '引数')
Parent.vue
<template>
  <div class="parent">
    <Child @parent-event="parentEvent($event, argument)" />
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Child from '~/components/Child.vue'

export default Vue.extend({
  components: {
    Child
  },
  methods: {
    parentEvent(argument: string) {
      console.log(argument)
    }
  }
})
</script>

親コンポーネントから子コンポーネントのイベント(メソッド)を呼び出す方法

Parent.vue
<template>
  <div class="parent">
    <Child ref="child" />
    <button @click="parentEvent">子のイベントを呼び出す</button>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import Child from '~/components/Child.vue'

export default Vue.extend({
  components: {
    Child
  },
  methods: {
    parentEvent() {
      this.$refs.child.childEvent()
    }
  }
})
</script>

Child.vue
<template>
  <div class="child"></div>
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
  methods: {
    childEvent() {
      console.log('childEvent')
    }
  }
})
</script>

<style scoped></style>

親コンポネートで<Child ref="child" /> ref属性を指定して、this.$refs.child.childEvent()で子コンポーネントのイベントを呼び出すことができます。

53
37
2

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
53
37