[Vuejs]-Custom event ($emit) in VueJS

0đź‘Ť

Any value passed as a prop is being “listened” on by the component that receives it. Thus, if the parent modifies this value, the child will have its own modified version overwritten with the parent’s new value. This can lead to unexpected behavior. Better is to have a copy of the value any time it changes. For example, you could use a “watched” property:

{
    props: [ "userAge" ],
    data: function() {
        return {
            myUserAgeCopy: null
        };
    },
    watch: {
        userAge: function() {
            this.myUserAgeCopy = this.userAge;
        }
    }
}

Then all further operations are performed on myUserAgeCopy instead.


Note that the above still results in the same data overwriting problem as with mutating the prop directly. What’s important is that now this overwriting is made explicit and predictable through the way you’ve written the code.


In general, if you need to keep the parent and child synchronized, you should always $emit any child-level changes, allow the parent to accept those changes, and then receive the $emitted changes in the child through the original prop:

child: {
    props: [ "userAge" ],
    data: function() {
        return {
            myUserAgeCopy: null
        };
    },
    watch: {
        userAge: function() {
            this.myUserAgeCopy = this.userAge;
        },
        myUserAgeCopy: function() {
            this.$emit('user_age_changed', this.myUserAgeCopy);
        }
    }
}

parent: {
    data: function() {
        return {
            userAge: 30
        };
    },
    methods: {
        handleUserAgeChange: function(userAge) {
            this.userAge = userAge;
        }
    }
}

<child :userAge="userAge" v-on:user_age_changed="handleUserAgeChange"/>

Leave a comment