vue 非父子组件之间的传值(Bus/总线/发布订阅模式/观察者模式)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>非父子组件之间的传值</title>        
        
    </head>
    <body>    
        <div id="app">
            <child content="Dell"></child>
            <child content="Lee"></child>
        </div>
        
        
        <!-- 开发环境版本,包含了用帮助的命令行警告 -->
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script type="text/javascript">
            Vue.prototype.bus = new Vue();
            Vue.component('child', {
                data: function() {
                    return {
                        selfContent: this.content
                    }                
                },
                props: {
                    content: String
                },
                template: `<div @click="handleClick">{{selfContent}}</div>`,
                methods: {
                    handleClick: function() {
                        this.bus.$emit('change', this.selfContent);
                    }
                },
                mounted: function() {
                    var _this = this;
                    this.bus.$on('change', function(msg) {
                        _this.selfContent = msg;
                    })
                }
                
            })
            var app = new Vue({
                el: '#app'                                
            })
            
        </script>
    </body>
</html>

猜你喜欢

转载自www.cnblogs.com/1032473245jing/p/9036074.html
今日推荐