vue:如何使传递给组件的对象反应?

2022-01-25 00:00:00 vue.js vue-component vuejs2

Codepen 演示

我有一个组件,它有一个 location 对象作为 props.我传入的参数是 locations[index],它是从 locations 数组中选择的项目.

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.

但是,当 index 更改时,组件无法做出反应.正如您在演示中看到的,当您单击按钮时,JSON 会发生变化,但组件无法更新.

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?

推荐答案

您的 location 组件会填充 provincecity 数据属性mounted 仅钩子.当 location 属性发生变化时,mounted 钩子将不会被再次调用,所以你会留下陈旧的数据.

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.

改用计算属性:

computed: {
  province() {
    return this.location.province;
  },
  city() {
    return this.location.city;
  }
}

更新的codepen

如果您确实需要 provincecity 作为数据属性(而不是计算属性),那么您将需要查看 location更新属性的道具:

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;
    }
  }
}

相关文章