这篇文章我们将使用组件化的思想来修改一下,之前实现的TodoList功能
全局化组件的实现方式:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>TodoList</title> <script src="./vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="inputTxt"> <button @click="submitEvent">提交</button> <ul> <todo-item v-bind:content="list" v-for="list in todoList" ></todo-item><!--向子组件传递绑定值 --> </ul> </div> <script> //创建全局组件 Vue.component('TodoItem',{ props:['content'],//接受传递的值 template:`<li>{{this.content}}</li>` }) var app = new Vue({ el: '#app', data:{ inputTxt:'', todoList: [] }, methods:{ submitEvent: function(){ this.todoList.push(this.inputTxt); this.inputTxt = ''; } } }) </script> </body> </html>
我们还可以使用子组件的方式:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>TodoList</title> <script src="./vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="inputTxt"> <button @click="submitEvent">提交</button> <ul> <todo-item v-bind:content="list" v-for="list in todoList" ></todo-item> </ul> </div> <script> //子组件 let TodoItem = { props:['content'], template:`<li>{{this.content}}</li>` }; var app = new Vue({ el: '#app', data:{ inputTxt:'', todoList: [] }, methods:{ submitEvent: function(){ this.todoList.push(this.inputTxt); this.inputTxt = ''; } }, components:{ TodoItem: TodoItem } }) </script> </body> </html>