[英]Removing an item from array: Wrong item being removed
我有一個帖子頁面,其中包含媒體附件列表。 我希望用戶單擊“刪除”鏈接時能夠手動刪除附件。 此事件正在運行,但是問題是實際刪除的項目不是被單擊的項目! 我究竟做錯了什么?
這是我的代碼和現場演示:[ codeandbox ]( 單擊 POSTS- >選擇一個帖子ID以查看帖子詳細信息->單擊EDIT post )
EditPost.vue
<template>
部分:
...snip..
<ul>
<li>Media Attachments
<template>
<ul v-if="attachmentsFileNames && attachmentsFileNames.length">
<li v-for="(mediaAttachment, index) in attachmentsFileNames" :key="index">
<a href="#">{{ mediaAttachment }}</a>
<button @click.prevent="deleteMediaAttachment(mediaAttachment, index)">Delete me!</button>
</li>
</ul>
<p v-else>No Media Attachments</p>
</template>
</li>
</ul>
EditPost.vue
<script>
:
...snip..
data() {
return {
post: {},
editPostFormIsVis: false,
attachmentsArray: attachments
};
},
created() {
this.getPost();
},
methods: {
getPost() {
axios
.get(
"https://jsonplaceholder.typicode.com/posts/" + this.$route.params.id
)
.then(resp => {
this.post = resp.data;
})
.catch(err => {
console.log(err);
});
},
editPost() {
this.editPostFormIsVis = true;
},
deleteMediaAttachment: function(item, index) {
if (this.attachmentsArray.attachments[index] === item) {
// The template passes index as the second parameter to avoid indexOf,
// it will be better for the performance especially for one large array
// (because indexOf actually loop the array to do the match)
this.attachmentsArray.attachments.splice(index, 1);
} else {
let found = this.attachmentsArray.attachments.indexOf(item);
this.attachmentsArray.attachments.splice(found, 1);
}
}
},
computed: {
emailAttachmentsFileNames() {
if (this.attachmentsArray.emailAttachments) {
const emailAttachmentsFileNameArray = this.attachmentsArray.emailAttachments.map(
item => {
const tokens = item.split("/");
return tokens[tokens.length - 1];
}
);
return emailAttachmentsFileNameArray;
} else {
return null;
}
},
attachmentsFileNames() {
if (this.attachmentsArray.attachments) {
const attachmentsFileNameArray = this.attachmentsArray.attachments.map(
item => {
const tokens = item.split("/");
return tokens[tokens.length - 1];
}
);
return attachmentsFileNameArray;
} else {
return null;
}
}
}
...snip...
將您的deleteMediaAttachment函數更改為
deleteMediaAttachment: function(item, index) {
this.attachmentsArray.attachments.splice(index, 1);
},
您的問題是您從attachmentsFileNames
發送了項目,並嘗試將其與原始attachments
數組中的項目進行匹配。 第一個包含文件名,第二個包含完整路徑,因此它們將不匹配。 例如:
console.log(item); // star_wars_luke.jpeg
console.log(this.attachmentsArray.attachments[index]); // attachments/2019/201900002020/star_wars_luke.jpeg
這就是this.attachmentsArray.attachments[index] === item
為false
,然后this.attachmentsArray.attachments.indexOf(item)
返回-1
,因此this.attachmentsArray.attachments.splice(-1, 1)
始終刪除數組中的最后一項。
由於您自己是從this.attachmentsArray.attachments
解析了attachmentsFileNames
數組的,因此您可以正確地依賴於相應的index
,因此甚至不需要進行這些檢查。 只需刪除它們並運行this.attachmentsArray.attachments.splice(index, 1)
,它應該可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.