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

  

  

子组件的按钮按钮绑定点击事件,事件方法名为<代码> sendToParent()

  

该方法在子组件的方法中声明,实现功能<代码>。美元发出(cus-event, this.msg);

  

在父组件引入子组件,并给cus-event事件绑定doAction(事件)美元方法,该方法中<代码>。味精=e; console.log (e),

  

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

  

  

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

  

useChild方法在父组件的中的方法中声明,调用子组件中的方法,并传入参数str,即<代码>。美元refs.child1.getMsg (str);

  

而getMsg方法已经在子组件的方法中声明,其行为是<代码> console.log>   

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

  

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

        & lt; !DOCTYPE html>   & lt; html lang=癳n”比;   & lt; head>   & lt;元charset=皍tf - 8”比;   & lt; title>子向父通信& lt;/title>   & lt; style>   #应用{   边界:1 px固体蓝色;   宽度:500 px;   填充:20 px;   保证金:汽车;   border - radius: 8 px;   背景:紫红色;   }   #包装{   边界:1 px固体红;   宽度:400 px;   填充:20 px;   border - radius: 8 px;   背景:黄绿色;   margin-top: 20 px;   }   & lt;/style>   & lt;脚本src=" https://cdn.jsdelivr.net/npm/vue "祝辞& lt;/script>   & lt;/head>   & lt; body>   & lt; div id=坝τ谩北?   & lt; !——父组件——比;   & lt; h2>这是父组件& lt;/h2>   & lt; p>展示父级接收到的消息:{{味精}}& lt;/p>   & lt;按钮@click=" useChild (szStr)”在调用子组件的方法& lt;/button>   & lt; !——cus-event为子组件自定义的事件名;doAction(事件)美元为父组件的事件,参数美元事件不可少也不可写成其他——比;   & lt; !——参考表示组件的别名——比;   & lt;孩子@cus-event=" doAction(事件)美元“ref=癱hild1祝辞& lt;/child>   & lt;/div>   & lt;/body>   & lt;/html>   & lt;模板id=昂⒆印北?   & lt; div id=鞍捌鳌北?   & lt; !——子组件——比;   & lt; h3>这是子组件& lt;/h3>   & lt;按钮@click=皊endToParent”在向父组件发消息& lt;/button>   & lt;/div>   & lt;/template>   & lt; script>   让孩子={   模板:“#孩子”,   数据(){   返回{   味精:“子级消息的   };   },   方法:{   sendToParent () {//子组件只管发送消息,其中cus-event为自定义事件名(事件名不能写成驼峰法,多个单词用——连接),this.msg为要传递的参数。   这一点。美元发出(cus-event, this.msg);   },   getMsg (str) {   控制台。日志(“子级组件收到父级的内容”,str);   }   }   };//注意:。$(“#应用”)跟山实例内部el:“#应用”是等价的   新Vue ({   数据:{   味精:”,   szStr:“父级消息的   },   组件:{   孩子   },   方法:{   doAction (e) {   console.log(这个);   console.log (e);   这一点。味精=e;   },   useChild (str) {//调用子组件的方法//console.log(这个);//console.log参(。);//这个。美元refs.child1得到的子组件实例   美元。refs.child1.getMsg (str);   }   }   })。美元山(“#应用”);   & lt;/script>之前      

效果图   

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

  

  

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

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