【发布时间】:2021-05-08 02:58:54
【问题描述】:
这是我所拥有的,我会尽可能多地解释它:
-
我的 HTML 代码中有一个模式,如下所示:
<div id="favorites-modal-edit" class="modal"> <div class="modal-background"></div> <div class="modal-card px-4"> <header class="modal-card-head"> <p class="modal-card-title">Favorites</p> <button class="delete" aria-label="close"></button> </header> <section class="modal-card-body"> <div class="container"> <div id="favorites-modal-edit-wrapper" class="columns is-multiline buttons"> <favorites-edit-component v-for="(favorite, index) in favorites_list" :key="favorite.id" :favorite="favorite" /> </div> </div> </section> <footer class="modal-card-foot"> <button class="button" @click="addItem"> Add Item </button> </footer> </div> </div>
id="favorites-modal-edit" 是 Vue.js 应用程序,然后我有 <favorites-edit-component /> vue.js 组件。
这是我的 JS 代码:
我生成了我的favorites_list,它是一个对象数组,如下所示:
const favorites_list = [
{
id: 1,
name: 'Horse',
url: 'www.example.com',
},
{
id: 2,
name: 'Sheep',
url: 'www.example2.com',
},
{
id: 3,
name: 'Octopus',
url: 'www.example2.com',
},
{
id: 4,
name: 'Deer',
url: 'www.example2.com',
},
{
id: 5,
name: 'Hamster',
url: 'www.example2.com',
},
];
然后,我有我的vue.js 组件,它是favorites-edit-component,它接收@click="removeItem(this.index),它在索引上以未定义的形式返回。
Vue.component('favorites-edit-component', {
template: `
<div class="column is-half">
<button class="button is-fullwidth is-danger is-outlined mb-0">
<span>{{ favorite.name }}</span>
<span class="icon is-small favorite-delete" @click="removeItem(this.index)">
<i class="fas fa-times"></i>
</span>
</button>
</div>
`,
props: {
favorite: Object
},
methods: {
removeItem: function(index) {
this.$parent.removeItem(index);
},
}
});
然后我有 vue.js 应用程序,它是父应用程序,如下所示:
new Vue({
el: '#favorites-modal-edit',
// Return the data in a function instead of a single object
data: function() {
return {
favorites_list
};
},
methods: {
addItem: function() {
console.log('Added item');
},
removeItem: function(index) {
console.log(index);
console.log(this.favorites_list);
this.favorites_list.splice(this.favorites_list.indexOf(index), 1);
},
},
});
问题:
由于某种原因,每次我从列表中删除一个项目时,它都会删除列表中的最后一个项目,我不知道为什么会这样做,看看发生了什么:
这是我正在关注的指南:
How to remove an item from an array in Vue.js
每次触发remoteItem()函数时,该项目都会返回未定义,如下所示:
感谢所有帮助!
【问题讨论】:
标签: vue.js vuejs2 vue-component vuex