为什么这个 Vue 计算属性不是响应式的? [英] Why is this Vue computed property not reactive?
问题描述
我想要我的视图,使用作为 prop 传递的 id,在商店中查找对象的属性.存储中的对象异步出现,因此该对象可能不会立即出现.我希望视图能够对对象的最终外观做出反应.
<div><h1>{{title}}</h1>
</模板><脚本>导出默认{道具:['id'],计算:{小部件(){让路径 = `小部件/${this.id}`返回 this.$store.state.widgets[path]},标题 () {让小部件 = this.widget返回(小部件)?widget.data().fullName : '这里没什么可看的'}}}
使用 vuex 调试工具,我可以看到商店小部件对象从空开始,然后使用 widgets: { 'widgets/someId': { ... } }
进行设置,但我的 vue 没有似乎没有改变.标题保持 == '没什么...'.
我尝试制作这些方法,但我得到了相同的行为.我还尝试替换商店中的整个 widgets
对象,而不是一次替换一个道具(我认为这是必需的),但仍然没有运气.
我认为我的问题与这个问题非常相似,但那里的答案太简洁了.它只是说使用数据项",但我真的不知道那是什么或如何使用它(或为什么这会使 vue 具有反应性).
因为你看到它从空到有一些成员,所以你与 Vue 的 更改检测警告.
<块引用>Vue 无法检测属性的添加或删除.
你需要使用Vue.set
添加或删除成员时,即使在 Vuex 中也是如此.
I'd like my view, using an id passed as a prop, to lookup an object's property in the store. The object in the store appears asynchronously, so the object might not be present right away. I'd like the view to react to the object's eventual appearance.
<template>
<div>
<h1>{{ title }}</h1>
</div>
</template>
<script>
export default {
props: ['id'],
computed: {
widget () {
let path = `widget/${this.id}`
return this.$store.state.widgets[path]
},
title () {
let widget = this.widget
return (widget) ? widget.data().fullName : 'nothing to see here'
}
}
}
</script>
Using vuex debug tools, I can watch the store widgets object start out empty and then get set with widgets: { 'widgets/someId': { ... } }
, but my vue doesn't seem to pick up the change. The title remains == 'nothing...'.
I tried making these methods, but I get the same behavior. I also tried replacing the whole widgets
object on the store, instead of one prop at a time (I think that's a requirement), but still no luck.
I think my question is very similar to this one, but the answer there is too terse. It just says "use a data item", but I don't really know what that is or how to use it (or why that will make the vue reactive).
Mutations Follow Vue's Reactivity Rules
Since you're watching it go from empty to having some members, you are falling afoul of Vue's change detection caveats.
Vue cannot detect property addition or deletion.
You need to use Vue.set
when adding or deleting members, even in Vuex.
这篇关于为什么这个 Vue 计算属性不是响应式的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!