vue2.0自定義事件


我們知道父組件是使用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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM