Avoid mutation of component propsJS-0611
Props and events should be preferred for parent-child component communication, instead of this.$parent
or mutating props.
When Vue re-renders your component — which happens every time something changes — it will overwrite any changes you have made to your props.
This means that even if you try to mutate the prop locally, Vue will keep overwriting those changes.
We pass data down the the component tree using props. A parent component will use props to pass data down to it's children components. Those components in turn pass data down another layer, and so on. Then, to pass data back up the component tree, we use events.
We do this because it ensures that each component is isolated from each other. This way we can guarantee a few things that help us in thinking about our components:
- Only the component itself can change it's own state
- Only the parent of the component can change the props
If we come across any unintended behaviour, knowing with 100% certainty where these changes are coming from makes it much easier to track down. Keeping these rules makes our components easier to reason about.
Bad Practice
<template>
<div>
// value property is attribute of input
<input v-model="value" @click="openModal">
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
required: true
}
},
methods: {
openModal() {
this.value = 'test'
}
}
}
</script>
Recommended
<template>
<div>
<input :value="value" @input="$emit('input', $event.target.value)" @click="openModal">
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
required: true
}
},
methods: {
openModal() {
this.$emit('input', 'test')
}
}
}
</script>