放上代码:
1 <!DOCTYPE html> 2 <html lang="zh"> 3 <head> 4 <meta charset="UTF-8"> 5 <script src="https://unpkg.com/vue/dist/vue.js"></script> 6 <title></title> 7 <style type="text/css"> 8 #div_form{ 9 border:1px solid #990000; 10 width: 50%; 11 } 12 </style> 13 </head> 14 15 <body> 16 <div id="div_form"> 17 <form> 18 <label for="input_id">TODO:</label> 19 <input type="text" id="input_id" placeholder="e" v-model="input_data"/> 20 <button @click.prevent="Add">Add</button> 21 </form> 22 23 <ul> 24 <li 25 is="todo-item" 26 v-for="(todo,title) in todos" 27 :key="todo.id" 28 :title="todo.title" 29 v-on:remove="todos.splice(title, 1)" 30 ></li> 31 </ul> 32 33 <!-- <div v-for="(value,name) in todos"> 34 {{todos[name].id}} 35 </div> --> 36 </div> 37 38 <script type="text/javascript"> 39 Vue.component('todo-item',{ 40 template:` 41 <li> 42 {{ title }} 43 <button v-on:click="$emit('remove')">Remove</button> 44 </li> 45 `, 46 props: ['title'] 47 }) 48 49 50 new Vue({ 51 el:"#div_form", 52 data:{ 53 input_data:'', 54 todos:[ 55 { 56 id:1, 57 title:'sfdsf', 58 }, 59 { 60 id:2, 61 title:'dsad', 62 }, 63 { 64 id:3, 65 title:"fdsfdsf", 66 }, 67 ], 68 nextTodoId: 4 69 }, 70 methods:{ 71 Add:function(){ 72 this.todos.push({ 73 id: this.nextTodoId++, 74 title: this.input_data 75 }) 76 this.input_data = '' 77 } 78 } 79 }) 80 </script> 81 </body> 82 </html>
放上效果图: