Vue: Unintentional two-way binding when passing in object prop.

Created on 29 Dec 2018  路  3Comments  路  Source: vuejs/vue

Version

2.5.21

Reproduction link

https://jsfiddle.net/rupertraphael/rxnqg01w/1/

Steps to reproduce

Click either buttons to edit the corresponding messages using the given text input.

What is expected?

I think that testInput shouldn't be able to mutate the value of the messages without an event being emitted.

What is actually happening?

For some reason, the child component (testInput) is unexpectedly modifying parent component data (messages).


In an app that I'm developing, I have this page where users are able to see a list application-wide roles and in this page, I have a modal child component (let's call it edit-role) that pops up when a user clicks the edit button for a particular role. One of the props that edit-role takes in is a Role object which is indirectly used (through a watcher) to populate the fields of edit-role. Since, it is bad practice to directly mutate a prop, I've assigned a watcher for the prop so as soon as the prop changes, it is assigned to a data variable which is bound (using v-model) to the input fields for edit-role. As soon as I modify the role's name using an input field, the same role in the page/list (parent component) also changes.

Most helpful comment

fyi in v3 such mutation would be blocked and result in a warning.

All 3 comments

See the note at the end of One-way data flow:

Note that objects and arrays in JavaScript are passed by reference, so if the prop is an array or object, mutating the object or array itself inside the child component will affect parent state.

See @sirlancelot鈥檚 reply.

fyi in v3 such mutation would be blocked and result in a warning.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

robertleeplummerjr picture robertleeplummerjr  路  3Comments

bfis picture bfis  路  3Comments

hiendv picture hiendv  路  3Comments

6pm picture 6pm  路  3Comments

Jokcy picture Jokcy  路  3Comments