实现跨组件的事件通信
    实际上就是一个空的vue实例
    前提是组件存在
    一定要保证接受事件统一

    它就像一个公交车一样,来回输送人,将组件A输送到组件B,再将组件B输送到组件A; 这里A,B组件可以是父、子组件,也可以是兄、弟组件,或者两个没有任何关系的组件;

    1. /1.创建中央事件总线,这里在全局中定义
    2. var Bus = new Vue();
    3. //2.使用Bus中央事件总线在A组件中发送信息
    4. Bus.$emit('自定义事件名''$on发送过来的数据');
    5. //3.使用Bus中央事件总线在B组件中接收信息,接收的事件在created钩子函数中可以进行获取
    6. Bus.$on('自定义事件名'function(msg){
    7. //这里的msg就是发过来的数据,在这里接收
    8. console.log(msg)
    9. });

    image.png

    1. <div id="app">
    2. <login></login>
    3. <register></register>
    4. </div>
    5. <template id="login">
    6. <div>
    7. <h1>这是login组件</h1>
    8. <button @click="handleClick">点击传递数据</button>
    9. </div>
    10. </template>
    11. <template id="register">
    12. <div>
    13. <h1>这是register组件</h1>
    14. <p>{{name}}</p>
    15. </div>
    16. </template>
    17. <script src="./js/vue.js"></script>
    18. <script>
    19. //全局中定义
    20. const Bus=new Vue()
    21. Vue.component("login",
    22. {
    23. template: "#login",
    24. data() {
    25. return {
    26. msg: "login中的数据"
    27. }
    28. },
    29. methods:{
    30. handleClick(){
    31. Bus.$emit("dataclick",this.msg)
    32. }
    33. }
    34. })
    35. Vue.component("register",
    36. {
    37. template: "#register",
    38. data(){
    39. return{
    40. name:""
    41. }
    42. },
    43. created () {
    44. Bus.$on("dataclick",(item)=>{
    45. this.name=item
    46. })
    47. }
    48. })
    49. const vm = new Vue({
    50. el: "#app",
    51. data: {
    52. },
    53. methods: {
    54. },
    55. })
    56. </script>