问题
Codepen Demo
I have a component which has an location
object as props
. The argument I passed in is locations[index]
which is a selected item from a locations
array.
However, the component cannot react when the index
change. As you can see in the demo, the JSON change as you click the button, but the component cannot update.
What's the best way to make the component reactive?
回答1:
Your location
component populates the province
and city
data properties in the mounted
hook only. When the location
prop changes, the mounted
hook will not be called again, so you are left with stale data.
Use a computed property instead:
computed: {
province() {
return this.location.province;
},
city() {
return this.location.city;
}
}
Updated codepen
If you really do require province
and city
to be data properties (and not computed properties) then you will need to watch the location
prop to update the properties:
data() {
return {
province: null,
city: null
}
},
watch: {
location: {
immediate: true,
handler(loc) {
this.province = loc.province;
this.city = loc.city;
}
}
}
来源:https://stackoverflow.com/questions/51054508/vue-how-to-make-the-object-passed-to-component-reactive