Vue 组件通信

南笙酒味 提交于 2019-12-29 16:49:22

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

方法二、$emit/$on

这种方法通过一个空的Vue实例作为中央事件总线(事件中心),用它来触发事件和监听事件,巧妙而轻量地实现了任何组件间的通信,包括父子、兄弟、跨级。当我们的项目比较大时,可以选择更好的状态管理解决方案vuex。

1.具体实现方式:

var Event=new Vue(); Event.$emit(事件名,数据); Event.$on(事件名,data => {});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="vue.js"></script>
</head>
<body>
<div id="app">
    <hello1></hello1>
    <hello2></hello2>


</div>
<script>

    var Event= new Vue();
    Vue.component("hello1",{
        template:'<h2 v-on:click="startHandle">send</h2>',
        methods:{
            startHandle:function(){
                console.info("send");
                Event.$emit('data-a','hello');


            }

        }

    });
    var Event= new Vue();
    Vue.component("hello2",{
        template:"<h2>receive</h2>",
        methods:{
            printVal:function(val){
                console.info("printVla:"+val)

            }

        },
        mounted(){
            Event.$on('data-a',name=>{
                console.info('receive:'+name);
                this.printVal(name);

            })

        }

    });



    new Vue({

        el:"#app"

    });


</script>
</body>
</html>

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!