当前位置:Gxlcms > JavaScript > vue2.x 父组件监听子组件事件并传回信息的方法

vue2.x 父组件监听子组件事件并传回信息的方法

时间:2021-07-01 10:21:17 帮助过:12人阅读

本文介绍了vue2.x 父组件监听子组件事件并传回信息,分享给大家,希望此文章对各位有所帮助

利用vm.$emit

1、在父组件中引用子组件

  1. <child @from-child-msg="listenChildMsg"></child >

2、子组件中使用$emit发送事件

  1. this.$emit('from-child-msg', '这是子组件传递的消息');

demo

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. <style>
  9. * {
  10. padding: 0;
  11. margin: 0;
  12. }
  13. input, select {
  14. height: 30px;
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div id="app">
  20. <child value="name" @msg-from-child="getMsgFromChild"></child>
  21. </div>
  22. <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
  23. <script>
  24. Vue.component('child', {
  25. data: function () {
  26. return {
  27. val: this.value
  28. }
  29. },
  30. props: ['value'],
  31. methods: {
  32. handleClick () {
  33. this.$emit('msg-from-child', this.val)
  34. }
  35. },
  36. template: `
  37. <div><input type="text" v-model="val"><button type="button" @click="handleClick">确定</button></div>
  38. `
  39. })
  40. new Vue ({
  41. el: '#app',
  42. data: {
  43. },
  44. methods: {
  45. getMsgFromChild (v) {
  46. alert('msg: ' + v)
  47. }
  48. }
  49. })
  50. </script>
  51. </body>
  52. </html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

人气教程排行