vue:如何使传递给组件的对象反应? [英] vue: how to make the object passed to component reactive?

查看:34
本文介绍了vue:如何使传递给组件的对象反应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于vue:如何使传递给组件的对象反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆