2、組件間通訊(子組件傳值給父組件)html
經過事件的方式來完成數據的傳輸。vue
①在父組件中 定義一個方法,用來接收子組件所經過事件傳來的值函數
methods:{
recvMsg:function(msg){
//參數msg就是子組件經過事件出來的數據
}
}this
②綁定事件處理函數
事件通常狀況 都是自定義事件spa
<child-component @myEvent="recvMsg"></child-component>code
③在子組件觸發事件component
事件名,值
this.$emit('myEvent',myPhone)
//觸發一個叫作myEvent的事件,同時把第二個參數數據傳遞給事件對應的處理函數
總結:
在 Vue 中,父子組件的關係能夠總結爲 props down, events up。父組件經過 props 向下傳遞數據給子組件,子組件經過 events 給父組件發送消息。htm
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>組件間通訊子傳父</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <parent-component></parent-component> </div> <script> //經過事件的方式傳遞 // 綁定 -- 觸發 Vue.component("parent-component",{ data:function(){ return { sonMsg:"" } }, methods:{ //msg參數要拿子傳遞的值 recvMsg:function(msg){ console.log("父組件接收到子組件的數據"+msg); this.sonMsg = msg; } }, template:` <div> <h1>這是父組件</h1> <p>子組件傳來的數據爲:{{sonMsg}}</p> <hr/> <child-component @customEvent="recvMsg"></child-component> </div> ` }) Vue.component("child-component",{ methods:{ sendMsg:function(){ //來觸發綁定給子組件的自定義方法 //this.$emit("customEvent");第一個參數觸發 //this.$emit("customEvent");第二個參數傳值 this.$emit("customEvent","哈哈哈哈"); }, }, template:` <div> <h1>這是子組件</h1> <button @click="sendMsg">senToFather</button> </div> ` }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>
:::在子組件中 放上一個input,點擊按鈕 把用戶輸入的內容發給父組件blog
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>子與父之間的通訊</title> <script src="js/vue.js"></script> </head> <body> <div id="container"> <p>{{msg}}</p> <parent-component></parent-component> </div> <script> //建立父組件 Vue.component("parent-component",{ //data屬性 data:function(){ return{ sonMsg:"" } }, methods:{ recvMsg:function(msg){ this.sonMsg = msg } }, template:` <div> <h1>父組件</h1> <h4>子組件傳遞的數據:{{sonMsg}}</h4> <child-component @customEvent="recvMsg"></child-component> </div> ` }) //建立子組件 Vue.component("child-component",{ data:function(){ return { myInput:"" } }, methods:{ sendMsg:function(){ this.$emit("customEvent",this.myInput); } }, template:` <div> <h1>子組件</h1> <input type="text" v-model="myInput"/> <button @click="sendMsg">發送</button> </div> ` }) new Vue({ el:"#container", data:{ msg:"Hello VueJs" } }) </script> </body> </html>