'Why does a prop change not change data?
I'm trying to understand why changing a prop, used to provide an initial value, doesn't cause the data variable to change.
In the below example, changing the initialName
value passed in the parent component, also causes the initialName
to change in the child component. However, name
keeps the value it was originally initialized as. I believed, seemingly incorrectly, that changing a prop would re-render the component.
ChildComponent.vue
<template>
<div>
{{initialName}}
{{name}}
</div>
</template>
<script>
export default {
props: {
initialName: {
type: String,
default: '',
}
},
data() {
return {
name: this.initialName,
};
},
</script>
ParentComponent.vue
<template>
<ChildComponent :initialName="AnExampleName"/>
</template>
<script>
import ChildComponent from ChildComponent.vue
export default {
components: {
ChildComponent
}
</script>
I've been able to work around this by watching the prop and updating name
, however this doesn't feel like the best approach.
How come changing the prop doesn't change the data? Is there a better way to pass an initial value to a child component?
Solution 1:[1]
data
is meant to be static, so if you set it once, it will not be reactive afterwards.
It will change if you mutate it directly of course, like this this.name = 'updated value hi hi'
.
But it will not mutate if you update another prop/state elsewhere (like initialName
in your example).
A simple approach for this would be to use a computed
like this
<script>
export default {
props: {
initialName: {
type: String,
default: "",
},
},
computed: {
name() {
return this.initialName
}
},
};
</script>
This example proves that the usage of data
is NOT updating the name
value (initialName
is totally reactive) if you do use it like the OP did. The usage of computed
solves this issue tho.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |