javascript - 无法从组件数组中删除元素(切片、Vue.js)
问题描述
我正在尝试在 Vue.js 中实现动态添加和删除组件。
slice 方法存在问题,基本上它应该通过传递的索引从数组中删除元素。要改变数组,我使用slice(i,1)。
根据这个答案,以这种方式修改数组应该对我有帮助,但不起作用。
我做错了什么?
这是我的代码和代码笔:
<div id="app">
<button @click="addNewComp">add new component</button>
<template v-for="(comp,index) in arr">
<component
:is="comp"
:index="index"
@remove-comp="removeComp(index)"
></component>
</template>
</div>
<script type="text/x-template " id="compTemplate">
<h1> I am a component {{index}}
<button v-on:click="$emit('remove-comp')">X</button>
</h1>
</script>
const newComp = Vue.component("newComp",{
template:"#compTemplate",
props:['index']
})
new Vue({
el:"#app",
data:{
arr:[newComp]
},
methods:{
addNewComp:function(){
this.arr.push(newComp);
console.log(this.arr);
},
removeComp:function(i){
console.log(i);
this.arr.slice(i,1);
console.log(this.arr);
}
}
})
解决方案
const newComp = Vue.component("newComp",{
template:"#compTemplate",
props:['index']
})
new Vue({
el:"#app",
data:{
arr:[newComp]
},
methods:{
addNewComp:function(){
this.arr.push(newComp);
},
removeComp:function(i, a){
console.log('i', i, a, typeof i);
this.arr.splice(i,1);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17-beta.0/vue.js"></script>
<div id="app">
<button @click="addNewComp">add new component</button>
<template v-for="(comp,index) in arr">
<component
:is="comp"
:index="index"
@remove-comp="removeComp(index, 100+index)"
:key="`${index}`"
></component>
</template>
</div>
<script type="text/x-template " id="compTemplate">
<h1> I am a component {{index}}
<button v-on:click="$emit('remove-comp')">X</button>
</h1>
</script>
我在与 Vue 和反应状态有关之前阅读了这篇文章。
.slice()
是非反应性的,因此它返回数据的副本而不更改原始数据(即非反应性)。使用.splice()
which 是响应式的,甚至更好地查看.filter()
这里
推荐阅读
- c# - 在 LEFT OUTER 连接上使用 Linq 删除“重复”结果
- django - Django - 在其依赖之前应用迁移
- swift - 更改 TableView 单元格中 UILabel 的前导和尾随约束(聊天气泡)
- java - 无法将类 java.lang.Integer 转换为类 java.lang.String
- php - QuickBook Online API 不包括运输服务行项目的折扣
- python - 如何使球小部件被 kivy 中的矩形小部件偏转?
- redis - 在给定的时间窗口内,处理主题中每个消费者的最大任务数?
- javascript - SignalR - 更新特定用户(推送通知)
- python - 使用 discord.py 创建角色
- d3.js - 带有水平标签的 d3v4 饼图