Vue.js实现的表格增加删除demo示例

Vue.js是当下很火的一个JavaScript MVVM库,它是以数据驱动和组件化的思想构建的。相比于Angular.js,Vue.js提供了更加简洁、更易于理解的API,使得我们能够快速地上手并使用Vue.js。

使用本站在线HTML/CSS/JavaScript代码运行工具,得到如下所示的运行效果:

Vue.js实现的表格增加删除demo示例

具体代码如下:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Vue.js小demo</title> <link href="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" > <style> label{float:left;line-height: 34px;} .panel-body{ margin:30px auto; } </style> </head> <body> <!-- 这是我们的view --> <div> <div > <div> <div> <label>Name:</label> <input type="text" v-model="newPerson.name"/> </div> <div> <label>Age:</label> <input type="text" v-model="newPerson.age"> </div> <div> <label>Sex:</label> <select v-model="newPerson.sex"> <option value="Male">Male</option> <option value="Female">Female</option> </select> </div> <div> <label></label> <button @click="createPerson">Create</button> </div> </div> <div> <table> <thead> <tr > <th>Name</th> <th>Age</th> <th>Sex</th> <th>Delete</th> </tr> </thead> <tbody> <tr v-for="person in people"> <td>{{ person.name }}</td> <td>{{ person.age }}</td> <td>{{ person.sex }}</td> <td><button v-on:click="delPerson($index)">Delete</button></td> </tr> </tbody> </table> </div> </div> </div> </body> <script src="https://cdn.bootcss.com/vue/2.2.6/vue.js"></script> <script> //创建一个Vue实例或"ViewModel",它连接view与model var vm = new Vue({ el: '#app', data: { newPerson: { name: '', age: '', sex: 'Male' }, people: [{ name: 'Jack', age: 30, sex: 'Male' }, { name: 'Bill', age: 26, sex: 'Male' }, { name: 'Tracy', age: 22, sex: 'Female' }, { name: 'Chris', age: 36, sex: 'Male' }] }, methods:{ createPerson: function(){ this.people.push(this.newPerson); // 添加完newPerson对象后,重置newPerson对象 this.newPerson = {name: '', age: '', sex: 'Male'} }, delPerson: function(index){ // 删一个数组元素 this.people.splice(index,1); } } }); </script> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/973e195489f20b7b83beca80fb917eca.html