天天看點

21$emit與$on

emit與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>      
  1. 定義一個中介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>      

繼續閱讀