gpt4 book ai didi

javascript - 从数组中删除一个项目 : Wrong item being removed

转载 作者:行者123 更新时间:2023-12-02 23:06:40 25 4
gpt4 key购买 nike

我有一个帖子页面,其中包含媒体附件列表。我希望用户在单击“删除”链接时能够手动删除附件。该事件正在运行,但是,问题是实际被删除的项目不是被单击的项目!我做错了什么?

这是我的代码和现场演示:[ codesandbox ](点击帖子-->选择帖子 ID 以查看帖子详细信息-->点击编辑帖子)

EditPost.vue <template> section:

...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>&nbsp;
<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);
},

关于javascript - 从数组中删除一个项目 : Wrong item being removed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57559018/

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