时间:2021-07-01 10:21:17 帮助过:12人阅读
本文介绍了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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。