子组件之间传递数据.html 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  6. <title>子组件之间传递数据</title>
  7. <meta name="description" content="">
  8. <meta name="keywords" content="">
  9. <link href="" rel="stylesheet">
  10. <script type="text/javascript" src='../js/vue.min.js'></script>
  11. </head>
  12. <body>
  13. <div id='app'>
  14. <foo>组件1</foo>
  15. <hr>
  16. <bar>组件2</bar>
  17. </div>
  18. <script type="text/javascript">
  19. //利用 eventBus 作为一个中间中转站,去实现兄弟之间的通信
  20. var eventBus = new Vue({});
  21. var foo = {
  22. template: `<button @click='addBar'>{{fooCount}}</button>`,
  23. data() {
  24. return {
  25. fooCount: 0
  26. }
  27. },
  28. methods: {
  29. addBar: function() {
  30. eventBus.$emit('addBar')
  31. }
  32. },
  33. mounted() {
  34. //再次借用了eventBus
  35. eventBus.$on('addFoo', function() {
  36. this.fooCount++
  37. }.bind(this))
  38. }
  39. }
  40. var bar = {
  41. template: `<button @click='addFoo'>{{barCount}}</button>`,
  42. data: function() {
  43. return {
  44. barCount: 0
  45. }
  46. },
  47. methods: {
  48. addFoo: function() {
  49. console.log(eventBus);
  50. eventBus.$emit('addFoo')
  51. }
  52. },
  53. mounted() {
  54. eventBus.$on('addBar', function() {
  55. this.barCount++
  56. }.bind(this))
  57. }
  58. }
  59. new Vue({
  60. el: '#app',
  61. components: {
  62. foo,
  63. bar
  64. }
  65. })
  66. </script>
  67. </body>
  68. </html>