时间:2020-10-13 13:22:16 | 栏目:vue | 点击:次
本文介绍了vue2.x 父组件监听子组件事件并传回信息,分享给大家,希望此文章对各位有所帮助
利用vm.$emit
1、在父组件中引用子组件
<child @from-child-msg="listenChildMsg"></child >
2、子组件中使用$emit发送事件
this.$emit('from-child-msg', '这是子组件传递的消息');
demo
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> * { padding: 0; margin: 0; } input, select { height: 30px; } </style> </head> <body> <div id="app"> <child value="name" @msg-from-child="getMsgFromChild"></child> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script> <script> Vue.component('child', { data: function () { return { val: this.value } }, props: ['value'], methods: { handleClick () { this.$emit('msg-from-child', this.val) } }, template: ` <div><input type="text" v-model="val"><button type="button" @click="handleClick">确定</button></div> ` }) new Vue ({ el: '#app', data: { }, methods: { getMsgFromChild (v) { alert('msg: ' + v) } } }) </script> </body> </html>