Humoyun Ahmad
Humoyun Ahmad

Reputation: 3082

Vue2: changing data property of child component based on a prop from a parent component

I have a modal window component in my child component which should be triggered when a user clicks a button in my parent component. I am passing triggering prop to the child and assigned it to the data property in child component. But when button clicked it is not reflected in data property. After searching, a little bit I found the case. But I could not find the solution to my problem. I tried with computed properties, but set() of a computed property is being called until it reaches stack overflow! So please could someone provide the best way to achieve my goal: changing data property of child component based on a prop from a parent component

Upvotes: 0

Views: 304

Answers (1)

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>

Upvotes: 2

Related Questions