Vue完成 TodoList 1.預設方式 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>TodoList</title> <script src="../../vue.js"></script> </he ...
Vue完成 TodoList
1.預設方式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>TodoList</title> <script src="../../vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="inputValue"> <button v-on:click="addItem">添加</button> <ul> <li v-for="item in list">{{ item }}</li> </ul> </div> <script> var app = new Vue({ el:'#app', data:{ list:[], inputValue:'' }, methods:{ addItem:function () { this.list.push(this.inputValue) this.inputValue = '' } } }) console.log(app.$data) </script> </body> </html>View Code
2.以全局組件的方式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="../../vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="inputValue"> <button v-on:click="addItem">添加</button> <tode-item v-bind:content="item" v-for="item in list"></tode-item> </div> <script> var Myconponent = Vue.extend({ props:['content'], template:"<li>{{content}}</li>" }) Vue.component('tode-item',Myconponent) var app = new Vue({ el:'#app', data:{ list:[], inputValue:'' }, methods:{ addItem:function () { this.list.push(this.inputValue) this.inputValue = '' } } }) </script> </body> </html>View Code
3.以局部組件的方式
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>局部組件 TodoList</title> <script src="../../vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="inputValue"> <button v-on:click="addItem">添加</button> <todo-item v-bind:content="item" v-for="item in list"></todo-item> </div> <script> var Myconponent = { props:['content'], template:"<li>{{content}}</li>" } var app = new Vue({ el:'#app', components:{ 'todo-item':Myconponent }, data:{ list:[], inputValue:'' }, methods:{ addItem:function () { this.list.push(this.inputValue) this.inputValue = '' } } }) </script> </body> </html>View Code
Vue 組件間傳值
子組件向父組件傳值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>局部組件 TodoList</title> <script src="../../vue.js"></script> </head> <body> <div id="app"> <input type="text" v-model="inputValue"> <button v-on:click="addItem">添加</button> <!--v-bind簡寫:: v-on: @--> <todo-item :content="item" :index="index" @delete="HandleItemDelete" v-for="(item,index) in list"></todo-item> </div> <script> var Myconponent = { props:['content','index'], template:"<li @click='HandleItemClick'>{{content}}</li>", methods:{ HandleItemClick:function () { this.$emit('delete',this.index) } } } var app = new Vue({ el:'#app', components:{ 'todo-item':Myconponent }, data:{ list:[], inputValue:'' }, methods:{ addItem:function () { this.list.push(this.inputValue) this.inputValue = '' }, HandleItemDelete:function (index) { console.log(index) this.list.splice(index,1) } } }) </script> </body> </html>View Code