我正在尝试从父组件中的对象中删除键。子组件将事件(带有项目值)发送回父方法,该方法触发父数据对象中的删除。
父组件:
data() {
return {
savedNews: Object
}
},
methods: {
containsKey(obj, key) {
var result = Object.keys(obj).includes(key)
return result
},
handleSaveNews(item) {
if (!this.containsKey(this.savedNews, item.url)) {
this.savedNews = {
[item.url]: item,
...this.savedNews
}
} else {
console.log(this.containsKey(this.savedNews, item.url))
var res = delete(this.savedNews, item.url)
console.log(res)
console.log(this.containsKey(this.savedNews, item.url))
}
}
}
最后一个 else 语句中的所有 console.log
都返回 true。提示删除成功,但 key 还在。如何删除该 key ?
最佳答案
来自the docs :
Vue cannot detect property addition or deletion
使用this.$delete
:
this.$delete(this.savedNews, item.url)
或this.$set
(也应用于属性更改):
this.$set(this.savedNews, item.url, undefined);
额外信息: $
是 Vue 用于每个组件实例上可用的内置方法的命名约定。有一些插件也选择遵循这种模式。例如,如果您 import Vue
并使用 Vue.delete
,您还可以在其他模块中使用内置函数。您可以添加自己的方法,例如 Vue.prototype.$mymethod = ...
。
关于vue.js - Vue 键不会从对象中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61114538/