0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

vue.js コンポーネント間のデータのやりとり

Last updated at Posted at 2020-08-17

vueコンポーネント間でデータを送る方法は 親⇒子 と 子⇒親 の場合で異なる。

親⇒子 propsでデータを受け取る

子コンポーネントのexport default{} 内でpropsオプションでプロパティを用意する。

child.vue
<script>
export default {
    props: {
        x: {
            type: Number,
            default: 1
        },
    }
}
</script>

ここでxは数値型、初期値1で宣言しているが、
props: ['x']と変数だけ用意してもいい。

親コンポーネント側で子を呼び出す際に属性としてデータを渡すことができる。

parent.vue
<template>
  <Child :x="10"></Child>
</template>

子⇒親 $emitでデータを送る

子コンポーネントでカスタムイベントである$emitを用意する。

child.vue
<template>
<div>
    <button @click="clickAction">x</button>
</div>
</template>

<script>
export default {
    props: {
        x: {
            type: Number,
            default: 1
        },
    },
    methods: {
        clickAction() {
            this.$emit("clicked", this.x + 100);
        }
    }
}
</script>

ここでは<button>を押した際のアクションとして$emitが発火される。

送られた値は、親コンポーネント側では$eventで受け取ることができる。

parent.vue
<template>
  <Child v-on:clicked="y = $event"></Child>
</template>

ここでは親のyという変数で受け取っている。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?