当前位置:Gxlcms > JavaScript > vue中的event bus非父子组件通信解析

vue中的event bus非父子组件通信解析

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

有时候非父子关系的组件也需要通信。在简单的场景下,使用一个空的Vue实例作为中央事件总线:

  1. var bus = new Vue()
  2. // 触发组件 A 中的事件
  3. bus.$emit('id-selected', 1)
  4. // 在组件 B 创建的钩子中监听事件
  5. bus.$on('id-selected', function (id) {
  6. // ...
  7. })

在更多复杂的情况下,你应该考虑使用专门的 状态管理模式.就是用到了vuex

eventBus是作为兄弟关系的组件之间的通讯中介。

代码示例:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>eventBus</title>
  5. <script src="http://cdn.jsdelivr.net/vue/1.0.28/vue.min.js"></script>
  6. </head>
  7. <body>
  8. <div id="todo-app">
  9. <h1>todo app</h1>
  10. <new-todo></new-todo>
  11. <todo-list></todo-list>
  12. </div>
  13. <script>
  14. var eventHub = new Vue( {
  15. data(){
  16. return{
  17. todos:['A','B','C']
  18. }
  19. },
  20. created:function () {
  21. this.$on('add', this.addTodo)
  22. this.$on('delete', this.deleteTodo)
  23. },
  24. beforeDestroy:function () {
  25. this.$off('add', this.addTodo)
  26. this.$off('delete', this.deleteTodo)
  27. },
  28. methods: {
  29. addTodo: function (newTodo) {
  30. this.todos.push(newTodo)
  31. },
  32. deleteTodo: function (i) {
  33. this.todos.splice(i,1)
  34. }
  35. }
  36. })
  37. var newTodo = {
  38. template:`<div><input type="text" autofocus v-model="newtodo"/><button @click="add">add</button></div>`,
  39. data(){
  40. return{
  41. newtodo:''
  42. }
  43. },
  44. methods:{
  45. add:function(){
  46. eventHub.$emit('add', this.newtodo)
  47. this.newtodo = ''
  48. }
  49. }
  50. }
  51. var todoList = {
  52. template:`<ul><li v-for="(index,item) in items">{{item}} \
  53. <button @click="rm(index)">X</button></li> \
  54. </ul>`,
  55. data(){
  56. return{
  57. items:eventHub.todos
  58. }
  59. },
  60. methods:{
  61. rm:function(i){
  62. eventHub.$emit('delete',i)
  63. }
  64. }
  65. }
  66. var app= new Vue({
  67. el:'#todo-app',
  68. components:{
  69. newTodo:newTodo,
  70. todoList:todoList
  71. }
  72. })
  73. </script>
  74. </body>
  75. </html>

效果图如下:

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

人气教程排行