案例:用元件通訊完成事件的新增、刪除
阿新 • • 發佈:2019-01-08
1. 父元件傳值給子元件:v-bind:'atrName' = '來自父元件的資料' , props['atrName']定義在子元件中接收來自父元件中的資料
2.子元件傳值給父元件:
方式一:(1)父元件中定義接收資料的物件陣列名list,(2)子元件中定義需要傳輸的資料inputText,(3)子元件中定義方法用this.$parent.list.push['inputText'],即可將資料傳遞給list
方法二:父元件中使用子元件,並在子元件標籤中新增屬性並給屬性賦值,(1)<son @toFather =‘recEvent’ >,(2)子元件中新增方法用this.$emit('toFather','來自子元件的資料'),(3)父元件中新增方法並且名字為recEvent= function(results){},resutls即為接收到的子元件資料
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>vue template</title> <script src="../js/vue.js"></script> </head> <body> <div id="example"> <to-do-box></to-do-box> </div> <script type="text/x-template" id="box-template"> <div> <to-do-input ></to-do-input> <to-do-list :myList="list" @toBox="recEvent"></to-do-list> </div> </script> <script type="text/x-template" id="input-template"> <div> <p>待做事項列表:</p> <input type="text" v-model="inputText"> <button @click="handleAdd">add</button> </div> </script> <script type="text/x-template" id="list-template"> <ul> <to-do-item v-for="temp in myList" :content="temp" @toList="recEvent"></to-do-item> </ul> </script> <script type="text/x-template" id="item-template"> <li> <button @click="handleDelete">delete</button> <span>{{content}}</span> </li> </script> <script type="text/javascript"> Vue.component('to-do-box',{ template:`#box-template`, data:function(){ return { list:[] } }, methods:{ recEvent:function(results){ console.log("data in box: " + results); this.list.pop(results); } } }); Vue.component('to-do-input',{ template:`#input-template`, data:function(){ return { inputText:'' } }, methods:{ handleAdd:function(){ this.$parent.list.push(this.inputText);//使用$parent直接將v-model中的的值inputText傳遞給父元件的list陣列 } } }); Vue.component('to-do-list',{ template:`#list-template`, // 父元件傳過來的值放在了繫結的屬性變數myList中,myList的具體值為父元件的list陣列 props:['myList'], methods:{ recEvent:function(results){ console.log("recEvent in list:" + results); this.$emit('toBox',results); } } }); Vue.component('to-do-item',{ template:`#item-template`, props:['content'], methods:{ handleDelete:function(){ this.$emit('toList',this.content); console.log("content in item: "+this.content); } } }); new Vue({ el: "#example", data: { myValue: "test!" } } ); </script> </body> </html>