1. 程式人生 > 實用技巧 >表單新增刪除

表單新增刪除

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h3>新增學員</h3>
        姓名:<input type="text" v-model='name'>
        <br>
        年齡:
<input type="text" v-model='age'> <br> <button @click='add'>新增</button> <button @click='reset'>重置</button> <h3>資訊表</h3> <table border="1" cellpadding='0' cellspacing='0' style="border-collapse:collapse;width:500px;"> <tr> <th>序號</th> <th>姓名</th> <th>年齡</th> <th>操作</th> </tr> <tr v-for
='(item,index) in arr' :key='item.id'> <td>{{index+1}} </td> <td>{{item.name}} </td> <td>{{item.age}} </td> <td> <button @click='del(index)'>刪除</button> </td> </tr> <tr v-if
='arr.length>0'> <td colspan="4"> <button @click='delAll'>全部刪除</button> </td> </tr> <tr v-else> <td colspan="4">暫無資料</td> </tr> </table> </div> <script src="./程式碼/vue.js"></script> <script> new Vue({ el:"#app", data:{ name:'', age:'', arr:[ { id:1, name:"aaa", age:11 }, { id:2, name:"bbb", age:11 }, { id:3, name:"ccc", age:11 }, { id:4, name:"ddd", age:11 } ] }, methods:{ // 刪除 del(index){ this.arr.splice(index,1) }, // 全部刪除 delAll(){ this.arr=[] }, // 新增 add(){ this.arr.push({ name:this.name, age:this.age }), this.reset() }, // 重置 reset(){ this.name='', this.age='' } } }) </script> </body> </html>