108
86

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 5 years have passed since last update.

Vue.jsでコンポーネント親子間の値の受け渡し

Posted at

親→子(データ)

  • 子のコンポーネントを読み込みテンプレートで配置
  • message="渡したいデータを代入"
parent.vue
<template>
    <div>
        <child message="Hello Vue!!"></child>
    </div>
</template>
<script>
import Child from './child.vue';
export default {
    components: {
        Child
    }
}
</script>

  • propsに「message」を設定
child.vue
<template>
    <div>
        <p>{{ message }}</p>
    </div>
</template>
<script>
export default {
    props: ['message']
}
</script>

親→子(変数)

  • dataに変数を設定
  • :message=messageで変数を渡す
parent.vue
<template>
    <div>
        <child :message="message"></child>
    </div>
</template>
<script>
import Child from './child.vue';
export default {
    components: {
        Child
    },
    data() {
        return {
            message: 'Hello Vue!!'
        }
    }
}
</script>

子→親(変数)

  • this.$parentでアクセス
child.vue
<script>
export default {
    created: function () {
        this.$parent.message = 'child!!!';
    }
}
</script>

子→親(メソッド)

  • v-on:panretMessage="messageLog"
parent.vue
<template>
    <div>
        <child v-on:panretMessage="messageLog"></child>
    </div>
</template>
<script>
import Child from './child.vue';
export default {
    components: {
        Child
    },
    methods: {
        messageLog() {
            console.log("parent");
        }
    }
}
</script>
  • $emit('panretMessage')
child.vue
<template>
    <div>
        <button @click="$emit('panretMessage')">message</button>
    </div>
</template>

メソッドに引数を渡す

parent.vue
export default {
    components: {
        Child
    },
    methods: {
        messageLog(message) {
            console.log(message);
        
    }
}
  • $emit('panretMessage', '親に送るメッセージ')
child.vue
<template>
    <div>
        <button @click="$emit('panretMessage', '親に送るメッセージ')">message</button>
    </div>
</template>
108
86
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
108
86

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?