动态DOM元素随Vue添加/删除 [英] Dynamic DOM elements add/remove with Vue
问题描述
我已经开始学习Vue.js,但我想不起来像在jQuery中那样,如何在Vue.js中做到这一点:
I have started to learn Vue.js and i can't figure it out how would you do this in Vue.js like I did it with jQuery:
<!-- jQuery -->
<h2>jQuery</h2>
<table id="t1">
<tr>
<th>Item</th>
<th>Quantity</th>
</tr>
<tr id="r1">
<td><input name="item[]" type="text"/></td>
<td><input name="quantity[]" type="number"/></td>
<td><button class="deleteRow">X</button></td>
</tr>
</table>
<button id="addRow">Add Row</button>
.js
// jQuery
$(document).on('click', '#addRow', function(){
var row = parseInt($('#t1 tr:last-child').attr('id')) + 1;
alert(row);
$('#t1').append('<tr id="r'+row+'"><td><input name="item[]" type="text"/></td><td><input name="quantity[]" type="number"/></td><td><button class="deleteRow">X</button></td></tr>');
});
$(document).on('click', '.deleteRow', function(){
var row = parseInt($(this).closest('tr').attr('id'));
$('#r'+row).remove();
});
如何使用Vue在点击上创建全新元素以及如何将其删除?
How to create a whole new element on a click with Vue and how to remove it?
这里全部加载到 JSFiddle
推荐答案
VueJS是数据驱动的,因此请不要直接进行DOM操作.
VueJS is data driven, so forget on direct DOM manipulations.
在下面的示例中,您将看到我已经定义了inputs
数组-这是我们将存储所有行的位置-因此它将是对象数组.
In example below, you will see that I've defined the inputs
array - that's the place where would we store all rows - so it would be array of objects.
在我们的模板中,我们遍历inputs
数组,并且对于每个输入,我们也发送索引-行删除是必需的.
In our template we're iterating through the inputs
array and for each input we send index too - required for row deleting.
addRow
是将新对象推送到我们的inputs
数组(具有预定义架构)的方法,并为其赋予唯一索引.
addRow
is method push new object to our inputs
array (with predefined schema), and give it unique index.
以下是示例: http://jsbin.com/zusokiy/edit?html ,js,输出
模板:
<div id="app">
<ul>
<li v-for="(input, index) in inputs">
<input type="text" v-model="input.one"> - {{ input.one }}
<input type="text" v-model="input.two"> - {{ input.two }}
<button @click="deleteRow(index)">Delete</button>
</li>
</ul>
<button @click="addRow">Add row</button>
</div>
JS:
const app = new Vue({
el: '#app',
data: {
inputs: []
},
methods: {
addRow() {
this.inputs.push({
one: '',
two: ''
})
},
deleteRow(index) {
this.inputs.splice(index,1)
}
}
})
更好的选择可能是将其分解为组件,但这到目前为止,还不错.
Better option would be maybe break it into components, but this is so far, so good.
这篇关于动态DOM元素随Vue添加/删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!