Vue子组件向父组件通信与父组件调用子组件中的方法

2019-11-16,,,

子组件向父组件通信

子组件的button按钮绑定点击事件,事件方法名为sendToParent(),

该方法在子组件的methods中声明,实现功能this.$emit('cus-event',this.msg);

在父组件引入子组件,并给cus-event事件绑定doAction($event)方法,该方法中this.msg = e;console.log(e),

而msg已经在data中声明,其值为”子级消息”,故最终的输出结果为: 展示父级接收到的消息:子级消息

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

点击父组件的button按钮,触发了click事件指向的useChild方法[该方法的行为是输出”父级消息”],

useChild方法在父组件的中的methods中声明,调用子组件中的方法,并传入参数str,即this.$refs.child1.getMsg(str);

而getMsg方法已经在子组件的methods中声明,其行为是console.log('子级组件收到父级的内容',str);,

所以,最终的输出结果为: 子级组件收到父级的内容 父级消息

代码示例(结合上面的分析理解代码)

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <title>子向父通信</title> 
  <style> 
    #app { 
      border: 1px solid blue; 
      width: 500px; 
      padding: 20px; 
      margin: auto; 
      border-radius: 8px; 
      background: fuchsia; 
    } 
    #wrapper { 
      border: 1px solid red; 
      width: 400px; 
      padding: 20px; 
      border-radius: 8px; 
      background: yellowgreen; 
      margin-top: 20px; 
    } 
  </style> 
  <script src="https://cdn.jsdelivr.net/npm/vue"></script> 
</head> 
<body> 
  <div id="app"> 
    <!-- 父组件 --> 
    <h1>这是父组件</h1> 
    <p>展示父级接收到的消息:{{msg}}</p> 
    <button @click="useChild(szStr)">调用子组件的方法</button> 
     <!-- cus-event为子组件自定义的事件名; doAction($event)为父组件的事件,参数$event不可少也不可写成其他--> 
    <!-- ref表示组件的别名 --> 
    <child @cus-event="doAction($event)" ref="child1"></child> 
  </div> 
</body> 
</html> 
<template id="child"> 
  <div id="wrapper"> 
    <!-- 子组件 --> 
    <h2>这是子组件</h2> 
    <button @click="sendToParent">向父组件发消息</button> 
  </div> 
</template> 
<script> 
  let child = { 
    template: '#child', 
    data() { 
      return { 
        msg: '子级消息' 
      }; 
    }, 
    methods: { 
      sendToParent() { 
        // 子组件只管发送消息,其中cus-event为自定义事件名(事件名不能写成驼峰法,多个单词用-连接),this.msg为要传递的参数。 
        this.$emit('cus-event', this.msg); 
      }, 
      getMsg(str) { 
        console.log('子级组件收到父级的内容', str); 
      } 
    } 
  }; 
  // 注意: .$mount('#app')跟实例内部el: '#app'是等价的 
  new Vue({ 
    data: { 
      msg: '', 
      szStr:'父级消息' 
    }, 
    components: { 
      child 
    }, 
    methods: { 
      doAction(e) { 
        console.log(this); 
        console.log(e); 
        this.msg = e; 
      }, 
      useChild(str) { 
        // 调用子组件的方法 
        // console.log(this); 
        // console.log(this.$refs); 
        // this.$refs.child1得到的子组件实例 
        this.$refs.child1.getMsg(str); 
      } 
    } 
  }).$mount('#app'); 
</script> 

效果图

总结

以上所述是小编给大家介绍的Vue子组件向父组件通信与父组件调用子组件中的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对北冥有鱼网站的支持!

您可能感兴趣的文章:

  • vue父组件向子组件动态传值的两种方法
  • vue.js中父组件调用子组件的内部方法示例
  • vue父组件中获取子组件中的数据(实例讲解)
  • vue父组件通过props如何向子组件传递方法详解
  • Vue中父组件向子组件通信的方法
  • 详解vue2父组件传递props异步数据到子组件的问题
  • 详解vue.js2.0父组件点击触发子组件方法
  • Vue2.x中的父组件传递数据至子组件的方法
  • vue的props实现子组件随父组件一起变化

《Vue子组件向父组件通信与父组件调用子组件中的方法.doc》

下载本文的Word格式文档,以方便收藏与打印。