[Vue] Parent and Child component communcation

By building components, you can extend basic HTML elements and reuse encapsulated code. Most options that are passed into a Vue constructor can be passed into a component. Each instance of a component has an isolated scope. Data can only be passed one direction and it must be from parent to child using props. To communicate with the parent element, use the $emitmethod.

Child component:

<template>
    <section>
        <h1>Child component {{name }}</h1>
        <div>
            Child button: <button @click="insideInc">Inc from inside {{insideCounter}}</button>
        </div>
    </section>
</template>

<script>
    export default {
        name: 'item-description',
        props: ['counter', 'name'],
        data: function() {
            return {
                insideCounter: this.counter
            }
        },
        methods: {
            insideInc() {
                this.insideCounter += 1;
                this.$emit('total', this.insideCounter);
            }
        }
    }
</script>

From parent, we will receive:

props: ['counter', 'name'],

And we rename 'counter' from parent to 'insideCounter':

        data: function() {
            return {
                insideCounter: this.counter
            }
        },

If we want to tell parent component, we can use '$emit':

this.$emit('total', this.insideCounter);

From parent component:

        <item-description
            v-bind:counter = "counter"
            v-bind:name = "message"
            @total="getTotalFromChild"
        ></item-description>
<script>

  import ItemDescription from '../components/item-description';
    components: {
        ItemDescription
    },

..

</script>
原文地址:https://www.cnblogs.com/Answer1215/p/6347417.html