天天看点

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>      

继续阅读