Vue中父子组件通信与事件触发的深入讲解

 更新时间:2022年03月22日 11:32:10   作者:小阿妍  
组件是Vue核心功能之一,合理的组件化,可以减少我们代码的冗余,提高项目的可维护性,下面这篇文章主要给大家介绍了关于Vue中父子组件通信与事件触发的相关资料,需要的朋友可以参考下

一、组件

子组件

<template>
  <div style="border:1px solid black;width:400px; height: 130px;">
    <h3>我是子组件</h3>
    <button>子组件将值传递给父组件</button>
    <div>子组件接收父组件的值:</div>
  </div>
</template> 

父组件

<template>
 <div style="border:1px solid red;padding:2rem;width:400px;margin:0 auto;">
    <h3>我是父组件</h3>
    <div>子组件向父组件传递的值:</div>
    <Child></Child>
  </div>
</template>

<script>
import Child from './Child';
export default {
    components: {
        Child
    }
}
</script>

效果展示:

通过这张图可以看出父子组件的结构,下面我们来实习父子组件通信。

二、父子组件通信

父组件给子组件通信

实现思路:子组件通过 props 来接受父组件传过来的值。

  • 在父组件中,定义一个data变量,在子组件标签中动态绑定这个值。

    // Father.vue
    <template>
     <div style="border:1px solid red;padding:2rem;width:400px;margin:0 auto;">
        <h3>我是父组件</h3>
        <div>子组件向父组件传递的值:{{ChildMsg}}</div>
        <Child :FatherMsg="data"></Child>
      </div>
    </template>
    
    <script>
    import Child from './Child';
    export default {
        data() {
            return {
                data: 'I am your father',
            }
        },
        components: {
            Child
        }
    }
    </script>
  • 接着在子组件里通过 props 来接收,这样子组件就接收到了父组件传递过来的值了。

    // Child.vue
    <template>
      <div style="border:1px solid black;width:400px; height: 130px;">
        <h3>我是子组件</h3>
        <button>子组件将值传递给父组件</button>
        <div>父组件向子组件传递的值:{{FatherMsg}}</div>
      </div>
    </template> 
    
    <script>
    export default {
        data() {
            return {
                data: 'I am your children',
            }
        },
        props: ['FatherMsg']
    }
    </script>

可以看到,我们父组件向子组件通信已经实现了,接下来就是子组件向父组件通信了,这个就要使用到 this.$emit 方法了。

子组件向父组件通信

实现思路:通过在子组件中使用 this.$emit 来触发自定义事件并传值,然后在父组件中监听该事件即可。

  • 在子组件中给 button 按钮添加 click 事件,来通过 this.$emit 自定义事件,并传入一个参数:

    <template>
      <div style="border:1px solid black;width:400px; height: 130px;">
        <h3>我是子组件</h3>
        <button @click="send">子组件将值传递给父组件</button>
        <div>父组件向子组件传递的值:{{FatherMsg}}</div>
      </div>
    </template> 
    
    <script>
    export default {
        data() {
            return {
                data: 'I am your children',
            }
        },
        props: ['FatherMsg'],
        methods: {
          send() {
            this.$emit('ListenChild', this.data);
          }
        }
    }
    </script>
  • 在父组件中的子组件标签里,先在 data 里定义一个变量接收这个值,然后监听在子组件中自定义的事件,并接受这个参数赋值给定义的变量:

    <template>
     <div style="border:1px solid red;padding:2rem;width:400px;margin:0 auto;">
        <h3>我是父组件</h3>
        <div>子组件向父组件传递的值:{{ChildMsg}}</div>
        <Child :FatherMsg="data" @ListenChild="ListenChild"></Child>
      </div>
    </template>
    
    <script>
    import Child from './Child';
    export default {
        data() {
            return {
                data: 'I am your father',
                ChildMsg: '',
            }
        },
        components: {
            Child
        },
        methods: {
            ListenChild(data) {
                console.log("子组件传递过来的值:" , data);
                this.ChildMsg = data;
            }
        }
    }
    </script>

点击子组件中的“子组件将值传递给父组件”,就可看到如下效果:

三、父子组件事件触发

父组件调用子组件中的事件方法

  • 通过 ref 直接调用子组件的方法:

    // Child.vue 
    <template>
      <div style="border: 1px solid black; width: 150px; margin: 10px auto">
        我是子组件
        <div style="color: red"> {{ msg }} </div>
      </div>
    </template>
    <script>
    export default {
        data() {
            return {
                msg: '',
            }
        },
      methods: {
        childFun() {
          console.log('我是子组件的方法 childFun');
          this.msg = '我的方法被调用了'
        },
      },
    };
    </script>

    在子组件标签上添加 ref 属性,然后在方法中通过 this.$refs 找到绑定 ref 的属性调用该子组件内的方法即可。

    // Father.vue
    <template>
      <div style="border: 1px solid red; width: 200px; padding: 10px; margin: 0 auto">
        我是父组件
        <Button @click="handleClick">点击调用子组件方法</Button>
        <Child ref="child" />
      </div>
    </template>    
    
    <script>
    import Child from './Child';
    
    export default {
        components: {
            Child
        },
        methods: {
            handleClick() {
                this.$refs.child.childFun();
            },
        },
    }
    </script>
  • 通过组件的 $emit$on 方法:

    // Child.vue 
    <template>
      <div style="border: 1px solid black; width: 150px; margin: 10px auto">
        我是子组件
        <div style="color: red"> {{ msg }} </div>
      </div>
    </template>
    <script>
    export default {
        data() {
            return {
                msg: '',
            }
        },
      mounted() {
        this.$on('childFun', function() {
            console.log('我是子组件方法');
            this.msg = '我的方法被调用了'
        });
      }
    };
    </script>

    在子组件中使用 $on 绑定一个方法,然后在父组件中通过 $emit 找到绑定 $on 上面的事件名即可,但是也需要 ref 的配合。

    // Father.vue
    <template>
      <div style="border: 1px solid red; width: 200px; padding: 10px; margin: 0 auto">
        我是父组件
        <Button @click="handleClick">点击调用子组件方法</Button>
        <Child ref="child" />
      </div>
    </template>    
    
    <script>
    import Child from './Child';
    
    export default {
        components: {
            Child
        },
        methods: {
            handleClick() {
            	//子组件$on中的名字
                this.$refs.child.$emit("childFun")    
            },
        },
    }
    </script>

两种实现方式效果一致。

调用方法前:

调用方法后:

子组件调用父组件中的事件方法

  • 直接在子组件中通过 this.$parent 来调用父组件的方法

    // Father.vue
    <template>
      <div style="border: 1px solid red; width: 200px; padding: 10px; margin: 0 auto" >
        我是父组件
        <Child></Child>
        <div style="color: red"> {{ msg }} </div>
      </div>
    </template>
    <script>
      import Child from './Child';
      export default {
          data() {
              return {
                  msg: ''
              }
          },
        components: {
          Child
        },
        methods: {
          fatherMethod() {
            console.log('我的父组件中的方法');
            this.msg = '我的方法被子组件调用了';
          }
        }
      };
    </script>
    // Child.vue
    <template>
      <div style="border: 1px solid black; width: 150px; margin: 10px auto">
        我是子组件
        <button @click="childMethod">点击调用父组件方法</button>
      </div>
    </template>
    <script>
      export default {
        methods: {
          childMethod() {
            this.$parent.fatherMethod();
          }
        }
      };
    </script>
  • 在子组件里用 $emit 向父组件触发一个事件,父组件监听这个事件(推荐使用)

    // Father.vue
    <template>
      <div style="border: 1px solid red; width: 200px; padding: 10px; margin: 0 auto" >
        我是父组件
        <Child @fatherMethod="fatherMethod"></Child>
        <div style="color: red"> {{ msg }} </div>
      </div>
    </template>
    <script>
      import Child from './Child';
      export default {
          data() {
              return {
                  msg: ''
              }
          },
        components: {
          Child
        },
        methods: {
          fatherMethod() {
            console.log('我的父组件中的方法');
            this.msg = '我的方法被子组件调用了';
          }
        }
      };
    </script>

    子组件可以使用 $emit 触发父组件的自定义事件。

    // Child.vue
    <template>
      <div style="border: 1px solid black; width: 150px; margin: 10px auto">
        我是子组件
        <button @click="childMethod">点击调用父组件方法</button>
      </div>
    </template>
    <script>
      export default {
        methods: {
          childMethod() {
            // fatherMethod父组件方法
            this.$emit('fatherMethod'); 
          }
        }
      };
    </script>
  • 父组件把方法传入子组件中,在子组件里直接调用这个方法:

    // Father.vue
    <template>
      <div style="border: 1px solid red; width: 200px; padding: 10px; margin: 0 auto" >
        我是父组件
        <Child :fatherMethod="fatherMethod"></Child>
        <div style="color: red"> {{ msg }} </div>
      </div>
    </template>
    <script>
      import Child from './Child';
      export default {
          data() {
              return {
                  msg: ''
              }
          },
        components: {
          Child
        },
        methods: {
          fatherMethod() {
            console.log('我的父组件中的方法');
            this.msg = '我的方法被子组件调用了';
          }
        }
      };
    </script>

    父组件可以将事件绑定到子组件标签上,子组件使用 props 接收父组件的事件。

    // Child.vue
    <template>
      <div style="border: 1px solid black; width: 150px; margin: 10px auto">
        我是子组件
        <button @click="childMethod">点击调用父组件方法</button>
      </div>
    </template>
    <script>
      export default {
        props: {
          fatherMethod: {
            type: Function,
            default: null
          }
        },
        methods: {
          childMethod() {
            if (this.fatherMethod) {
              this.fatherMethod();
            }
          }
        }
      };
    </script>

以上三种实现方式效果一致。

调用方法前:

调用方法后:

四、总结

至此,Vue 父子组件之间大部分的操作都涉及到了,我们在程序的开发过程中对于该部分内容可以游刃有余了。

到此这篇关于Vue中父子组件通信与事件触发的文章就介绍到这了,更多相关Vue父子组件通信与事件触发内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • vue通过指令(directives)实现点击空白处收起下拉框

    vue通过指令(directives)实现点击空白处收起下拉框

    这篇文章主要介绍了vue通过指令(directives)实现点击空白处收起下拉框,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • Vue中装饰器的使用示例详解

    Vue中装饰器的使用示例详解

    Vue Property Decorator提供了一些装饰器,包括@Prop、@Watch、@Emit、@Inject、@Provide、@Model等等,本文主要来和大家讲讲它们的使用方法,需要的可以参考一下
    2023-07-07
  • spring-cloud-stream的手动消息确认问题

    spring-cloud-stream的手动消息确认问题

    这篇文章主要介绍了spring-cloud-stream的手动消息确认问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-05-05
  • 使用vue-cli+webpack搭建vue开发环境的方法

    使用vue-cli+webpack搭建vue开发环境的方法

    这篇文章主要介绍了使用vue-cli+webpack搭建vue开发环境的方法,需要的朋友可以参考下
    2017-12-12
  • Webpack打包图片-js-vue 案例解析

    Webpack打包图片-js-vue 案例解析

    在开发中我们会有各种各样的模块依赖,这些模块可能来自于自己编写的代码,也可能来自第三方库,本文给大家介绍Webpack打包图片-js-vue的相关知识,感兴趣的朋友跟随小编一起看看吧
    2023-11-11
  • 在Vue中使用highCharts绘制3d饼图的方法

    在Vue中使用highCharts绘制3d饼图的方法

    本篇文章主要介绍了在Vue中使用highCharts绘制3d饼图的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • Vue路由守卫之路由独享守卫

    Vue路由守卫之路由独享守卫

    这篇文章主要介绍了Vue路由守卫之路由独享守卫的代码,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-09-09
  • vue设置默认首页的操作

    vue设置默认首页的操作

    这篇文章主要介绍了vue设置默认首页的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • vue实现微信分享链接添加动态参数的方法

    vue实现微信分享链接添加动态参数的方法

    这篇文章主要介绍了vue微信分享链接添加动态参数的实现方法,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2019-04-04
  • vue项目接入高德地图点击地图获取经纬度以及省市区功能

    vue项目接入高德地图点击地图获取经纬度以及省市区功能

    这篇文章主要给大家介绍了关于vue项目接入高德地图点击地图获取经纬度以及省市区功能的相关资料,开发中我们需要地图定位,就是用户输入位置,自动定位获取经纬度,需要的朋友可以参考下
    2023-08-08

最新评论