【发布时间】:2018-10-14 03:49:00
【问题描述】:
我已阅读使用 v-for here 在列表中呈现自定义组件的文档。
但由于某种原因,我无法使其正常工作。它总是删除最后一个组件,而不是我在索引中发送的那个。知道为什么它不起作用吗?
我的 VUE JS 版本是:2.5.16。
使用 PHPStorm IDE 并在 docker(linux 容器)上运行
和 Laravel 混合(我在 package.json 中有 "laravel-mix": "0.*" 条目)使用 webpack 并编译 JS 模块。
这是我的一些代码
// Parent Component JS
<template>
<ul>
<li
is="child-component"
v-for="(child, index) in componentList"
:key="index"
:myVal="Something...."
@remove="dropField(index)"
@add-custom-field="addField"
></li>
</ul>
</template>
<script>
import childComponent from './ChildComponent';
export default {
name: 'CustomList',
components: {'child-component' :childComponent},
data() {
return {
componentList: []
}
},
methods: {
addField() {
console.log('Handling add-custom-field field...');
this.componentList.push(childComponent);
},
dropField(index) {
console.log(`I am deleting the component with index = ${index} from listview in parent...`);
this.componentList.splice(index, 1);
}
}
}
// Child Component JS
<template>
<div>
<input type="text" v-model="currentValue" /><button @click.prevent="$emit('remove')" > Remove </button>
</div
</template>
<script>
export default {
props: { myVal : '' },
data() { return { currentValue: ''} },
created() {this.currentValue = this.myVal;}
}
</script>
【问题讨论】:
-
有几个可用的 JsFiddle 可以显示同样的问题已解决。我的代码似乎一切正常,但在 Chrome 中仍然无法运行......但我遇到的 jsFiddle 在同一个 chrome 浏览器中运行良好。
-
我让它在 JSFiddle 中工作 jsfiddle.net/andy1234/3f8ct86o
-
另外,如果您正在做相当复杂的事情,我建议您使用 Object 将您的组件存储为 {UniqueKey: VueComponent, ...} 然后为 Object 执行 v-for,因为它似乎可以工作与 Array 相比更好。
标签: vue.js vuejs2 vue-component