DEV Community

Julian Schäfer
Julian Schäfer

Posted on

Explained: Passing props to data - Why is my data not changing?

Today I found out something basic that I should have known for a long time. The value for a data-property, associated with a props-property, is only set when the component is initialized! Further changes to the prop will not be applied to the data-property.

An example

Lets assume we've got the following child component, which gets some name passed by its parent.

Child.vue:

export default {
  name: 'Child',
  props: {
    name: String,
  },
  data() {
    return {
      localName: this.name,
    };
  },
};
Enter fullscreen mode Exit fullscreen mode

A parent component can simple pass a name to this component. The initial data value inside Child is set to name, which is defined inside parent.

Runtime types with pass-by-value

I have always thought that this connection localName: this.name is passed by reference. So if you change the prop, you also change the data each time. But this is wrong!

Rather, it is passed by value, which means the value of this.name is copied and applied to localName. Therefore, only the initial value of this.name is applied to localName during rendering time of the component. Further changes are ignored unless the component is re-rendered.

This applies to all normal props-types like String, Number, or Boolean.

Array and Object are different

This could be the end of the article. However, there exists an exception.

Arrays and objects are passed by reference. So it is actually possible to mutate nested properties of the array or the object. Even if it is possible, you should not do it. For more information have a look at the official docs.

Example

I've also made an interactive example which demonstrates the behaviour of changing props and how it affects its related data property..

Summary

Keep this in mind if you change data in your parent component and it does not affect the local state of your child component.

This is my first article, so I would like to welcome any suggestions for improvement, feedback, or pointers to false claims.

Top comments (0)