[Vuejs]-Vue2: changing data property of child component based on a prop from a parent component

2👍

You can try use the following after code.

//parent.vue
<template>
    <div class="component">
        <p>Ten toi la {{ name }}</p>
        <p>Toi nam nay {{ age }} tuoi</p>
        <button @click="resetAge">Reset tuoi</button>
        <hr>

        <div class="row">
            <div class="col-xs-12 col-sm-6 col-6">
                <app-user-detail :age="age" @ageWasUpdated="age = $event"></app-user-detail>
            </div>
        </div>
    </div>
</template>
<script>
    import Child from './Child.vue';
    export default {
        data: function () {
            return {
                name: 'Duy',
                age: 23,
                todo:[
                    {
                        name:'A',
                        age:12
                    },
                     {
                        name:'B',
                        age:13
                    },
                     {
                        name:'C',
                        age:14
                    }
                ]
            };
        },

        components: {
            appUserDetail: Child,
        },
        methods: {
            resetAge () {
                this.age = 23
            }
        }
    }
</script>
//child.vue
<template>
    <div class="component">
        <h3>User Details</h3>
        <p>Tuoi toi:{{age}}</p>
        <button v-on:click="changeAge">Doi tuoi</button>
    </div>
</template>
<script>
	export default {
		props: ['age'],
		methods: {
		    changeAge () {
		        this.age = 24;
		        this.$emit('ageWasUpdated', this.age)
		    }
		}
	}
</script>

Leave a comment