vue组件间如何进行通信?方法介绍

梦丽姑娘_9759

梦丽姑娘_9759

2020-10-26

2491人浏览

转载

组件通信

尽管子组件可以用this.$parent访问它的父组件及其父链上任意的实例,不过子组件应当避免直接依赖父组件的数据,尽量显式地使用 props 传递数据。

另外,在子组件中修改父组件的状态是非常糟糕的做法,因为: 

  • 这让父组件与子组件紧密地耦合; 

  • 只看父组件,很难理解父组件的状态。因为它可能被任意子组件修改!理想情况下,只有组件自己能修改它的状态。

每个Vue实例都是一个事件触发器:

  • $on()——监听事件。

  • $emit()——把事件沿着作用域链向上派送。(触发事件)

  • $dispatch()——派发事件,事件沿着父链冒泡。

  • $broadcast()——广播事件,事件向下传导给所有的后代。

监听与触发

v-on监听自定义事件:

html>

    
        <meta>
        <title></title>
    
    
        <!--子组件模板-->
        <template>
            <input>
            <button>Dispatch Event</button>
        </template>
        <!--父组件模板-->
        <div>
            <p>Messages: {{ messages | json }}</p>
            <child></child>
        </div>
    
    <script></script>
    <script>
//        注册子组件
//        将当前消息派发出去
        Vue.component('child', {
            template: '#child-template',
            data: function (){
                return { msg: 'hello' }
            },
            methods: {
                notify: function() {
                    if(this.msg.trim()){
                        this.$dispatch('child-msg',this.msg);
                        this.msg = '';
                    }
                }
            }
        })
//        初始化父组件
//        在收到消息时将事件推入一个数组中
        var parent = new Vue({
            el: '#events-example',
            data: {
                messages: []
            },
            methods:{
                'handleIt': function(){
                    alert("a");
                }
            }
        })
    </script>

1.png

父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件:

html>

    
        <meta>
        <title></title>
    
    
        <div>
          <p>{{ total }}</p>
          <button-counter></button-counter>
          <button-counter></button-counter>
        </div>
    
    <script></script>
    <script>
        Vue.component('button-counter', {
          template: '<button v-on:click="increment">{{ counter }}',
          data: function () {
            return {
              counter: 0
            }
          },
          methods: {
            increment: function () {
              this.counter += 1
              this.$emit('increment')
            }
          },
        })
        new Vue({
          el: '#counter-event-example',
          data: {
            total: 0
          },
          methods: {
            incrementTotal: function () {
              this.total += 1
            }
          }
        })
    </script>

2.png

在某个组件的根元素上监听一个原生事件。可以使用 .native 修饰v-on 。例如:

<my-component></my-component>

派发事件——$dispatch()

html>

    
        <meta>
        <title></title>
    
    
        <div>
            <p>Messages: {{ messages | json }}</p>
            <child-component></child-component>
        </div>
        <template>
            <input>
            <button>Dispatch Event</button>
        </template>

    <script></script>
    <script>
        // 注册子组件
        Vue.component('child-component', {
            template: '#child-component',
            data: function() {
                return {
                    msg: ''
                }
            },
            methods: {
                notify: function() {
                    if (this.msg.trim()) {
                        this.$dispatch('child-msg', this.msg)
                        this.msg = ''
                    }
                }
            }
        })
    
        // 初始化父组件
        new Vue({
            el: '#app',
            data: {
                messages: []
            },
            events: {
                'child-msg': function(msg) {
                    this.messages.push(msg)
                }
            }
        })
    </script>
    

3.png

蓝湖代码转vue2.0+element-ui
蓝湖代码转vue2.0+element-ui

将静态 Vue 页面(index.vue)改造为动态页面(Custom.vue);稿源仅限 index.vue、其引用的 CSS 与资源路径,禁止参考仓库内其他文件。Invoke when user wants to transform a static Vue page into a dynamic data-driven page with Element UI components.

下载
  1. 子组件的button元素绑定了click事件,该事件指向notify方法

  2. 子组件的notify方法在处理时,调用了$dispatch,将事件派发到父组件的child-msg事件,并给该该事件提供了一个msg参数

  3. 父组件的events选项中定义了child-msg事件,父组件接收到子组件的派发后,调用child-msg事件。

广播事件——$broadcast()

html>

    
        <meta>
        <title></title>
    
    
        <div>
            <input>
            <button>Broadcast Event</button>
            <child-component></child-component>
        </div>
        
        <template>
            <ul>
                <li>
                    父组件录入了信息:{{ item }}
                </li>
            </ul>
        </template>

    <script></script>
    <script>
        // 注册子组件
        Vue.component('child-component', {
            template: '#child-component',
            data: function() {
                return {
                    messages: []
                }
            },
            events: {
                'parent-msg': function(msg) {
                    this.messages.push(msg)
                }
            }
        })
        // 初始化父组件
        new Vue({
            el: '#app',
            data: {
                msg: ''
            },
            methods: {
                notify: function() {
                    if (this.msg.trim()) {
                        this.$broadcast('parent-msg', this.msg)
                    }
                }
            }
        })
    </script>
    

和派发事件相反。前者在子组件绑定,调用$dispatch派发到父组件;后者在父组件中绑定,调用$broadcast广播到子组件。

父子组件之间的访问

  • 父组件访问子组件:使用$children或$refs

  • 子组件访问父组件:使用$parent

  • 子组件访问根组件:使用$root

$children:

html>

    
        <meta>
        <title></title>
    
    
        <div>
            <parent-component></parent-component>
        </div>
        
        <template>
            <child-component1></child-component1>
            <child-component2></child-component2>
            <button>显示子组件的数据</button>
        </template>
        
        <template>
            <h2>This is child component 1</h2>
        </template>
        
        <template>
            <h2>This is child component 2</h2>
        </template>
        <script></script>
        <script>
            Vue.component('parent-component', {
                template: '#parent-component',
                components: {
                    'child-component1': {
                        template: '#child-component1',
                        data: function() {
                            return {
                                msg: 'child component 111111'
                            }
                        }
                    },
                    'child-component2': {
                        template: '#child-component2',
                        data: function() {
                            return {
                                msg: 'child component 222222'
                            }
                        }
                    }
                },
                methods: {
                    showChildComponentData: function() {
                        for (var i = 0; i < this.$children.length; i++) {
                            alert(this.$children[i].msg)
                        }
                    }
                }
            })
        
            new Vue({
                el: '#app'
            })
        </script>
    

4.png

$ref可以给子组件指定索引ID:

html>

    
        <meta>
        <title></title>
    
    
        <div>
            <parent-component></parent-component>
        </div>
        
        <template>
            <!--<child-component1></child-component1>
            <child-component2></child-component2>-->
            <child-component1></child-component1>
            <child-component2></child-component2>
            <button>显示子组件的数据</button>
        </template>
        
        <template>
            <h2>This is child component 1</h2>
        </template>
        
        <template>
            <h2>This is child component 2</h2>
        </template>
        <script></script>
        <script>
            Vue.component('parent-component', {
                template: '#parent-component',
                components: {
                    'child-component1': {
                        template: '#child-component1',
                        data: function() {
                            return {
                                msg: 'child component 111111'
                            }
                        }
                    },
                    'child-component2': {
                        template: '#child-component2',
                        data: function() {
                            return {
                                msg: 'child component 222222'
                            }
                        }
                    }
                },
                methods: {
                    showChildComponentData: function() {
//                        for (var i = 0; i < this.$children.length; i++) {
//                            alert(this.$children[i].msg)
//                        }
                        alert(this.$refs.cc1.msg);
                        alert(this.$refs.cc2.msg);
                    }
                }
            })
            new Vue({
                el: '#app'
            })
        </script>
    

效果与$children相同。

$parent:

html>

    
        <meta>
        <title></title>
    
    
        <div>
            <parent-component></parent-component>
        </div>
        
        <template>
            <child-component></child-component>
        </template>
        
        <template>
            <h2>This is a child component</h2>
            <button>显示父组件的数据</button>
        </template>
        
        <script></script>
        <script>
            Vue.component('parent-component', {
                template: '#parent-component',
                components: {
                    'child-component': {
                        template: '#child-component',
                        methods: {
                            showParentComponentData: function() {
                                alert(this.$parent.msg)
                            }
                        }
                    }
                },
                data: function() {
                    return {
                        msg: 'parent component message'
                    }
                }
            })
            new Vue({
                el: '#app'
            })
        </script>
    

5.png

如开篇所提,不建议在子组件中修改父组件的状态。

 非父子组件通信

有时候非父子关系的组件也需要通信。在简单的场景下,使用一个空的 Vue 实例作为中央事件总线:

var bus = new Vue()
// 触发组件 A 中的事件
bus.$emit('id-selected', 1)
// 在组件 B 创建的钩子中监听事件
bus.$on('id-selected', function (id) {
    // ...
})
相关推荐:2020年前端vue面试题大汇总(附答案)vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程入门!!

前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

vue

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
js正则表达式
js正则表达式

php中文网为大家提供各种js正则表达式语法大全以及各种js正则表达式使用的方法,还有更多js正则表达式的相关文章、相关下载、相关课程,供大家免费下载体验。

2023.06.20

4696

8

js获取当前时间
js获取当前时间

JS全称JavaScript,是一种具有函数优先的轻量级,解释型或即时编译型的编程语言;它是一种属于网络的高级脚本语言,主要用于Web,常用来为网页添加各式各样的动态功能。js怎么获取当前时间呢?php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

2023.07.28

1395

5

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

2023.08.03

1838

5

js是什么意思
js是什么意思

JS是JavaScript的缩写,它是一种广泛应用于网页开发的脚本语言。JavaScript是一种解释性的、基于对象和事件驱动的编程语言,通常用于为网页增加交互性和动态性。它可以在网页上实现复杂的功能和效果,如表单验证、页面元素操作、动画效果、数据交互等。

2023.08.17

10243

11

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

2023.09.01

1020

4

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

2023.09.04

2944

5

Js中concat和push的区别
Js中concat和push的区别

Js中concat和push的区别:1、concat用于将两个或多个数组合并成一个新数组,并返回这个新数组,而push用于向数组的末尾添加一个或多个元素,并返回修改后的数组的新长度;2、concat不会修改原始数组,是创建新的数组,而push会修改原数组,将新元素添加到原数组的末尾等等。本专题为大家提供concat和push相关的文章、下载、课程内容,供大家免费下载体验。

2023.09.14

1609

5

js截取字符串的方法介绍
js截取字符串的方法介绍

JavaScript字符串截取方法,包括substring、slice、substr、charAt和split方法。这些方法可以根据具体需求,灵活地截取字符串的不同部分。在实际开发中,根据具体情况选择合适的方法进行字符串截取,能够提高代码的效率和可读性 。

2023.09.21

5069

3

js生成随机数方法
js生成随机数方法

JavaScript生成随机数的方法,包括使用Math.random()方法生成指定范围内的随机整数、生成随机字符串和生成随机颜色。根据具体需求,可以选择适合的方法来生成随机数,以实现各种功能 。

2023.09.25

2955

5

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
uni-app快速上手
uni-app快速上手

共0课时 | 0人学习

Vue 教程
Vue 教程

共42课时 | 17.4万人学习

Vue3.x 工具篇--十天技能课堂
Vue3.x 工具篇--十天技能课堂

共26课时 | 2.6万人学习