21$emit與$on

emitemit與on

$on $emit應用場景

  1. 子組件中觸發在父組件中定義的方法

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <div id="app"></div>
    </body>
    <script src="./node_modules/vue/dist/vue.min.js" type="text/javascript"></script>
    <script>
        let myButton = {
            template:`
            <button @click='showMsg'><slot></slot></button>
            `,
            methods:{
                showMsg(){
                    this.$emit('show');
                }
            }
        }
         new Vue({
            el:"#app",
            template:`
            <div>
                <myButton @show='showMsg'>按我</myButton>
            </div>
            `,
            components:{
                myButton
            },
            methods:{
                showMsg(){
                    alert("hahaha");
                }
            }
        })
     
    </script>
    </html>
    
  2. 定義一箇中介vue對象,在兄弟組件中傳值

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <div id="app"></div>
    </body>
    <script src="./node_modules/vue/dist/vue.min.js" type="text/javascript"></script>
    <script>
        let event = new Vue();
        let myButton = {
            template:`
            <button @click='showMsg'><slot></slot></button>
            `,
            methods:{
                showMsg(){
                    event.$emit('show');
                }
            }
        }
        new Vue({
            el:"#app",
            template:`
            <div>
                <myButton>按我</myButton>
            </div>
            `,
            components:{
                myButton
            },
            mounted(){
                event.$on('show',()=>{
                    alert("hahaha");
                })
            }
        })
    
    </script>
    </html>
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章