First up code
<body> <div id="root"> <div> <input v-model="inputValue" /> <button @click="handleClick">submit</button> </div> <ul> <todolist v-for="(item,index) of list" :key="index" :content="item" :index="index" @delete="handle" ></todolist> </ul> </div> <script> Vue.component("todolist",{ props: ['content','index'], template: '<li @click="handleDelete">{{content}}</li>', methods: { handleDelete:function(){ this.$emit('delete',this.index) } } }) new Vue({ el:"#root", data: { inputValue:'', list:[] }, methods: { handleClick:function(){ this.list.push(this.inputValue) this.inputValue='' }, handle:function(index){ this.list.splice(index,1) } } }) </script> </body>
Create the basic structure of todolist
1 <div id="root"> 2 <div> 3 <input v-model="inputValue" /> 4 <button @click="handleClick">submit</button> 5 </div> 6 <ul> 7 <todolist v-for="(item,index) of list" 8 :key="index" 9 :content="item" 10 :index="index" 11 @delete="handle" 12 ></todolist> 13 </ul> 14 </div>
Here we create a todolist tag as the parent component, let it loop through the list as our output, and define a delete listening event.
Next, define the subcomponents in the script tag
1 Vue.component("todolist",{ 2 props: ['content','index'], 3 template: '<li @click="handleDelete">{{content}}</li>', 4 methods: { 5 handleDelete:function(){ 6 this.$emit('delete',this.index) 7 } 8 } 9 })
A global type of child component is defined. The props option of the child component can receive data from the parent component. Props can only be delivered one-way, that is, it can only be delivered to the child component through the parent component. Here, the content and index of the parent component are passed down.
Take the li tag as the template of the sub component, add the listening event handleDelete and click the li tag to delete it.
Define the handleDelete method of the child component below, and use this.$emit to communicate with the parent component. Here, a delete event is passed in. The parameter is index. The parent component listens and receives the parameter through @ delete
Next is the Vue instance
1 new Vue({ 2 el:"#root", 3 data: { 4 inputValue:'', 5 list:[] 6 }, 7 methods: { 8 handleClick:function(){ 9 this.list.push(this.inputValue) 10 this.inputValue='' 11 }, 12 handle:function(index){ 13 this.list.splice(index,1) 14 } 15 } 16 })
The handleClick method adds values to the list every time the submit button is clicked, and clears the input box after each addition.
In the handle method, click to delete the li tag. Here, you can determine which li is clicked by accepting the incoming index parameter
This is before deleting:
This is after deletion:
Summary: click the li implementation of the child component to trigger a delete event. The parent component listens for the delete event of the child component, executes the handle method of the parent component, so as to delete the list item corresponding to the index, and the list item corresponding to the todolist will also be deleted.