link411 link412 link413 link414 link415 link416 link417 link418 link419 link420 link421 link422 link423 link424 link425 link426 link427 link428 link429 link430 link431 link432 link433 link434 link435 link436 link437 link438 link439 link440 link441 link442 link443 link444 link445 link446 link447 link448 link449 link450 link451 link452 link453 link454 link455 link456 link457 link458 link459 link460 link461 link462 link463 link464 link465 link466 link467 link468 link469 link470 link471 link472 link473 link474 link475 link476 link477 link478 link479 link480 link481 link482 link483 link484 link485 link486 link487 link488 link489 link490 link491 link492 link493 link494 link495 link496 link497 link498 link499 link500 link501 link502 link503 link504 link505 link506 link507 link508 link509 link510 link511 link512 link513 link514 link515 link516 link517 link518 link519 link520 link521 link522 link523 link524 link525 link526 link527 link528 link529 link530 link531 link532 link533 link534 link535 link536 link537 link538 link539 link540 link541 link542 link543 link544 link545 link546 link547

[Vue.js] Avoid mutating a prop directly in reusable components Subscribe to RSS

I’m trying to reuse a custom dropdown that there is created in my component file where props are the value options in dropdown. When i start to select the dropdown i realized a vue.js warn msg:

[vue.js warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value. Prop being mutated: “item”

What is the best practice & how I should write this in order to not have prop mutating value?

<template>
<v-app>
<SearchSelect
v-model=”newItem.a”
:options=”aList”></SearchSelect>
<SearchSelect
v-model=”newItem.b”
:options=”bList”></SearchSelect>
<SearchSelect
v-model=”newItem.c”
:options=”cList”></SearchSelect>
</v-app>
</template>

<script>
export default {
name: “Sales”,
data() {
return {
aList: [
{ value: “A1”, text: “A1” },
{ value: “A2”, text: “A2” },
{ value: “A3”, text: “A3” },
{ value: “A4”, text: “A4” },
{ value: “A5”, text: “A5” }
],
bList: [
{ value: “B1”, text: “B1” },
{ value: “B2”, text: “B2” },
{ value: “B3”, text: “B3” }
],
cList: [
{ value: “C1”, text: “C1” },
{ value: “C2”, text: “C2” },
{ value: “C3”, text: “C3” }
],
}
}
}
};
</script>

Solution :

Instead of mutating the property, you emit an event to the parent. The parent then mutates the value, and that new value is usually reflowed back down to the child’s property.

The v-model directive in the parent works by v-binding data it ‘owns’ to the :value property and listening for the @input v-on event.

In the case, the owner of newItem.a should be updating it, but most likely SearchSelect is setting it instead of emitting an event.

You can also avoid the $emit to the parent by using state management, in which case the store would be the source of truth; You would then commit or dispatch instead of emit.