美文网首页
vue2非父子组件间通讯

vue2非父子组件间通讯

作者: ChenDaXia | 来源:发表于2017-12-02 21:10 被阅读0次
<!DOCTYPE html>
<html>

<head>
    <!-- 声明文档使用的字符编码 -->
    <meta charset='utf-8'>
    <title>Title of the document</title>
    <script type="text/javascript" src="vue.js"></script>
</head>

<body>
    <div id="app">
        <p>{{ message }}</p>
        <component-a></component-a>
    </div>
</body>
<script>
    var bus = new Vue();
    Vue.component('component-a', {
        template: '<button @click="handleEvent">+1</button>',
        data: function() {
            return {
                counter: 0
            }
        },
        methods: {
            handleEvent: function() {
                bus.$emit('on-message', '来自组件component-a的内容')
            }
        }
    })
    var app = new Vue({
        el: '#app',
        data: {
            message: ''
        },
        mounted: function() {
            var _this = this;
            //在实例初始化时,监听来自bus实例的事件
            bus.$on('on-message', function(msg) {
                debugger;
                _this.message = msg;
            })

        },
        computed: {

        }
    })
</script>

</html>

相关文章

网友评论

      本文标题:vue2非父子组件间通讯

      本文链接:https://www.haomeiwen.com/subject/yqrobxtx.html