vue: how to make the object passed to component reactive?(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
组件会填充 province
和 city
数据属性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
如果您确实需要 province
和 city
作为数据属性(而不是计算属性),那么您将需要查看 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:如何使传递给组件的对象反应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:vue:如何使传递给组件的对象反应?


- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01