非父子组件间的传值

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>非父子组件传值(Bus/总线/发布订阅模式/观察者模式)</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="root">
        <child content="Dell"></child>
        <child content="Lee"></child>
    </div>
    <script>
        Vue.prototype.bus = new Vue()
        Vue.component('child', {
            props: {
                content: String
            },
            template: '<div @click="handleClick">{{ content }}</div>',
            methods: {
                handleClick: function() {
                    this.bus.$emit('change', this.content)
                }
            },
            mounted: function() {
                var this_ = this
                this.bus.$on('change', function(msg) {
                    this_.content = msg
                })
            }
        })
        var vm = new Vue({
            el: "#root",
        })
    </script>
</body>
</html>

这样做会报出警告,因为它不是一个单向数据流

解决方法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>非父子组件传值(Bus/总线/发布订阅模式/观察者模式)</title>
    <script src="./vue.js"></script>
</head>
<body>
    <div id="root">
        <child content="Dell"></child>
        <child content="Lee"></child>
    </div>
    <script>
        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 vm = new Vue({
            el: "#root",
        })
    </script>
</body>
</html>