gpt4 book ai didi

vue.js - 删除嵌套数组属性值时 UI 不更新,仅在添加时更新

转载 作者:搜寻专家 更新时间:2023-10-30 22:28:21 25 4
gpt4 key购买 nike

我有一个页面,其中从父组件传入具有嵌套数组值的对象。然后,用户可以使用一系列事件和组件来管理这些订阅中的数据。目前我遇到一个问题,当从 props 中删除 subscriptionId 时,页面上的条件不会改变,但在添加时会发生变化。

子组件

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

最佳答案

使用Vue.delete而不是 delete 关键字。

使用 delete 时对象不再可见,因此不是 react 性的。

Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

关于vue.js - 删除嵌套数组属性值时 UI 不更新,仅在添加时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51128348/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com