如何使用“v-for"用于添加或删除具有多个组件的行 [英] how to use "v-for" for adding or removing a row with multiple components
问题描述
我有一行包含 3 个组件(其中定义了组件 1、组件 2 和组件 3,如我之前的问题所示:VueJs 组件未定义 )
如何使用 v-for 添加一行或删除一行(其中有 3 个组件)?
var data1={selected: null, items:["A", "B"]};Vue.component('comp1', {模板:`<select v-model="selected"><option disabled value="">请选择</option><option v-for="item in items" :value="item">{{item}}</option></选择>`,数据:功能(){返回数据1}});<!---对于组件 2 和 3 类似--->新的 Vue({el: '#app',数据: {行:[]},方法:{添加行:函数(){this.rows.push({});},removeRow:函数(行){//console.log(row);this.rows.$remove(row);}},});
在 .html 中
<div id="应用程序"><div v-for ="行中行"><comp1></comp1><comp2></comp2><comp3></comp3><button @click="addRow">添加行</button><button @click="removeRow(row)">删除行</button>
代码非常接近.试试这个.
console.clear()常量模板 = {模板:`<select v-model="selected"><option disabled value="">请选择</option><option v-for="item in items" :value="item">{{item}}</option></选择>`,数据:函数(){返回 {选择:空,项目:[A",B"]}}};Vue.component("comp1", 模板)Vue.component("comp2", 模板)Vue.component("comp3", 模板)新的 Vue({el: '#app',数据: {行:[]},计算:{newId(){返回 this.rows.length == 0 ?1 : Math.max(...this.rows.map(r => r.id)) + 1}},方法: {添加行:函数(){this.rows.push({id: this.newId });},removeRow:函数(行){this.rows.splice(this.rows.indexOf(row), 1)}},});
<script src="https://unpkg.com/vue"></script><div id="应用程序"><div v-for="row in rows" :key="row.id"><comp1></comp1><comp2></comp2><comp3></comp3><button @click="removeRow(row)">删除行</button>
<button @click="addRow">添加行</button>