Reputation: 4779
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?
Upvotes: 3
Views: 6943
Reputation: 1461
Nested items in your prop location
won't be reactive, you'll need to use something like lodash deepClone :
<location :location.sync="_.deepClone(loc)"></location>
That's it, no need for watchers or anything else.
Upvotes: 0
Reputation: 34286
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;
}
}
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;
}
}
}
Upvotes: 4