[英]Delete object property (VueJs)
我有這個對象:
this.object = {
one: { ... },
two: { ... },
three: { ... }
}
例如,如何刪除屬性three
並使 UI 重新呈現? 我已經嘗試過使用delete
,但它似乎並沒有改變狀態並且 UI 沒有重新渲染。
當我使用this.object = { }
時,它會重新渲染 UI。 最后一個問題,這是什么類型的物體? 因為很難找到使用這種類型對象的示例或答案。
來自Vue Reactivity Guide (它沒有具體告訴你如何刪除)
Vue無法檢測到屬性添加或刪除
為了使這些突變具有反應性,您必須使用 Vue 的內置方法。 你可以這樣做:
this.$delete(this.object, 'three');
或者
this.$set(this.object, 'three', undefined);
要回答您關於對象的問題,它是一個對象文字。
演示:
Vue.config.productionTip = false; Vue.config.devtools = false new Vue({ el: "#app", data() { return { object: { one: {}, two: {}, three: {} } } }, methods: { deleteProp() { this.$delete(this.object, 'three'); //this.$set(this.object, 'three', undefined); } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> {{ object }} <button @click="deleteProp">Delete property</button> </div>
在組件中試試這個
<template>
<ul>
<li v-for="(obj,key) in object" @click="deleteKey(key)">{{obj}}</li>
</ul>
</template>
export default {
name: "YourComponent",
data: () => {
return {
object: {
one: {},
two: {},
three: {}
}
}
},
methods: {
deleteKey: function (key) {
this.$delete(this.object, key);
}
},
components: {Loader}
}
單擊列出的值時,它將被刪除並且可以看到 UI 發生變化。
做就是了:
this.object.three = { } // just make it empty, or
delete this.object.three // or
delete this.object['three']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.