vue: how to make the object passed to component reactive?

时光怂恿深爱的人放手 提交于 2021-01-03 07:41:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!