我們知道父組件是使用props傳遞數據給子組件,如果子組件要把數據傳遞回去,怎么辦? 那就是要自定義事件!使用v-on綁定自定義事件 每個Vue實例都實現了事件接口(Events interface), 即 使用$on(eventName) 監聽事件 $emit(eventName) 觸發事件
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="../vue2.2.js"></script> <!--<script src="../vue2.1.6.js"></script>--> <link rel="stylesheet" href="styles/demo.css" /> </head> <body><div id="app"> <table> <tr> <th colspan="3">父組件數據</th> </tr> <tr> <td>名字</td> <td>{{name}}</td> <td><input type="text" v-model="name" /></td> </tr> <tr> <td>年齡</td> <td>{{age}}</td> <td><input type="text" v-model="age" /></td> </tr> </table> <my-component :my-name="name" :my-age="age" @change-name="setName" @change-age="setAge"></my-component> </div> <template id="myComponent"> <table> <tr> <th colspan="3">子組件數據</th> </tr> <tr> <td>名字</td> <td>{{myName}}</td> <td><input type="text" v-model="myName" /></td> </tr> <tr> <td>年齡</td> <td>{{myAge}}</td> <td><input type="text" v-model="myAge" /></td> </tr> </table> </template> <script> var vm = new Vue({ el: "#app", data: { name: "小明", age: 24 }, components: { 'my-component': { template: "#myComponent", props: ["myName", "myAge"], watch: { //監聽外部對props屬性myName,myAge的變更 myName: function(val) { this.$emit("change-name", val) //組件內對myName變更后向外部發送事件通知 }, myAge: function(val) { this.$emit("change-age", val) //組件內對myAge變更后向外部發送事件通知 } } } }, methods: { setName: function(val) { this.name = val; //外層調用組件方法注冊變更方法,將組件內的數據變更,同步到組件外的數據狀態中 }, setAge: function(val) { this.age = val; } } }) </script> </body> </html>