我有一个页面,其中具有嵌套数组值的对象是从父组件传入的。然后,用户可以使用一系列事件和组件来管理这些订阅中的数据。目前,我遇到一个问题,当从subscriptionId
中删除props
时,页面上的条件没有改变,但添加时它们却改变了。
export default {
props: {
// Format of this object is:
// { "gameId": [
// 'subscriptionId',
// 'subscriptionId',
// ] }
subscriptions: {
type: Object,
required: true
}
},
watch: {
subscriptions: {
handler: function (newSubscriptions, oldSubscriptions) {
// NEVER gets fired when `subscriptionId` deleted from array list, but is fired when a new subscription is added
console.log('handler');
}
},
deep: true
}
},
我怀疑这可能与我从对象中删除数组的方式有关。本质上,我正在复制数组,删除有问题的索引并覆盖原始数组。我希望这种方法是不需要watcher
,但似乎没有影响。以下是父组件上用于更新订阅的代码:
// Works great, don't have any issues here
handleSubscribed (subscriptionId) {
let newSubscriptions = [subscriptionId];
if (this.subscriptions.hasOwnProperty(this.currentGame.id)) {
newSubscriptions = this.subscriptions[this.currentGame.id];
newSubscriptions.push(subscriptionId);
}
this.$set(this.subscriptions, this.currentGame.id, newSubscriptions);
},
handleUnsubscribed (subscriptionId) {
// if there's more than one, delete only the one we're looking for
if (this.subscriptions.hasOwnProperty(this.currentGame.id) && this.subscriptions[this.currentGame.id].length > 1) {
let newSubscriptions = this.subscriptions[this.currentGame.id];
delete newSubscriptions[newChannels.indexOf(subscriptionId)];
this.$set(this.subscriptions, this.currentGame.id, newSubscriptions);
// shows my subscription has been removed, but GUI doesn't reflect the change
console.log('remove-game', newSubscriptions);
return;
}
this.$delete(this.subscriptions, this.currentGame.id);
},
我希望watch
是解决方案,但事实并非如此。我已经看过几次反应式文档,却看不到为什么它不起作用的原因。
VueJS版本:2.5.7
答案 0 :(得分:0)
使用Vue.delete代替delete
关键字。
使用delete
时该对象不再可观察,因此无法反应。
删除对象上的属性。如果对象是反应性的,请确保删除触发视图更新。这主要是为了解决Vue无法检测到属性删除的限制,但您几乎不需要使用它。