首页 > 其他分享 >35-Vue脚手架-全局事件总线(使用全局事件总线优化Todo-List案例)

35-Vue脚手架-全局事件总线(使用全局事件总线优化Todo-List案例)

时间:2023-11-02 18:05:20浏览次数:25  
标签:School Vue 总线 List vue bus 组件 全局 hello

全局事件总线(GlobalEventBus)

1. 一种组件间通信的方式,适用于任意组件间通信

2. 安装全局事件总线

new Vue({
    ...
    // 生命周期 beforeCreate 这时vue还未解析模板,初始化的数据监测、数据代理还未开始
    beforeCreate() {
        // 安装全局事件总线
        Vue.prototype.$bus = this
    },
    ...
})

3. 使用事件总线

1)接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身

methods() {
    demo(data){...}
}

...

// 生命周期 mounted , 这时呈现的是经过 Vue编译的 DOM
mounted() {
    console.log("School",this)
    // 接收数据,在组件中给$bus绑定自定义事件
    this.$bus.$on("hello", this.demo}
}

2)提供数据:B组件想提供数据,也就是要触发在A组件绑定的事件

this.$bus.$emit("hello" , 数据)

4. 最好在生命周期beforeDestroy钩子中,用$off去解绑 当前组件所用到的 事件

beforeDestroy() {
      // 解绑自定义事件 hello
      this.$bus.$off("hello")
}

 

案例:使用全局事件总线,把Student组件的学生姓名属性,传递给School组件,并进行替换

src/components/School.vue(接收数据,以及解绑当前组件所用到的事件)

<template>
  <div class="school">
    <h2>学校名称:{{name}}</h2>
    <h2>学校地址:{{address}}</h2>
  </div>
</template>

<script>
  export default{
    // eslint-disable-next-line vue/multi-word-component-names
    name:"School",
    data(){
      return{
        name:"马铃薯的博客园",
        address:"河北省邯郸市"
      }
    },
    // 生命周期 mounted , 这时呈现的是经过 Vue编译的 DOM
    mounted() {
      console.log("School",this)
      // 监听当前实例上自定义事件hello
      // this.x.$on("hello",(data)=>{
      //   console.log("我是School组件,收到了数据:",data)
      // })
      this.$bus.$on("hello",(data)=>{
        console.log("我是School组件,收到了数据:",data)
        this.name = data
      })
    },
    beforeDestroy() {
      // 解绑自定义事件 hello
      this.$bus.$off("hello")
    }
  }
</script>

<style scoped>
  .school{
    background-color: skyblue;
    padding: 5px;
  }
</style>

src/components/Student.vue(提供数据)

<template>
  <div class="student">
    <h2>学生姓名:{{name}}</h2>
    <h2>学生性别:{{sex}}</h2>
    <button @click="sendStudentName">把学生姓名给School组件</button>
  </div>
</template>

<script>
  export default{
    // eslint-disable-next-line vue/multi-word-component-names
    name:"School",
    data(){
      return{
        name:"马铃薯",
        sex:"男",
      }
    },
    mounted() {
      console.log("Student",this)
    },
    methods:{
      sendStudentName() {
        // 触发当前实例上的自定义事件 hello
        // this.x.$emit("hello" ,666)
        this.$bus.$emit("hello" ,this.name)
      }
    }
  }
</script>

<style scoped>
  .student{
    background-color: pink;
    padding: 5px;
    margin-top: 30px;
  }
</style>

src/App.vue(无变动)

<template>
  <div class="app">
    <h1>{{msg}}</h1>

    <School></School>
    <Student></Student>

  </div>
</template>

<script>
  import Student from "@/components/Student.vue";
  import School from "@/components/School.vue"

  export default{
    name:"App",
    data(){
      return{
        msg:"你好啊"
      }
    },
    components:{
      Student:Student,
      School:School
    },
  }
</script>

<style>
 .app{
   background-color: gray;
   padding: 5px;
 }
</style>

src/main.js(安装全局事件总线)

import Vue from "vue"
import App from "./App.vue"

// 阻止 vue 在启动时生成生产提示
Vue.config.productionTip = false

// // 创建VueComponent实例对象
// const Demo = Vue.extend({})
// const d = new Demo()
//
//
// // Vue原型对象
// console.log(Vue.prototype)
//
// // vm和vc是存在一个重要的内置关系的: VueComponent.prototype.__proto__ === Vue.prototype
// // 让组件实例对象(vc)可以访问到 Vue原型上的属性、方法。
// Vue.prototype.x = d


new Vue({
    el:"#app",
    render:h => h(App),
    // 生命周期 beforeCreate 这时vue还未解析模板,初始化的数据监测、数据代理还未开始
    beforeCreate() {
        // 安装全局事件总线,这里的this指的是vm,不用vc实例对象了
        // Vue.prototype.x = this

        // $bus 更专业
        Vue.prototype.$bus = this
    }
})

 

标签:School,Vue,总线,List,vue,bus,组件,全局,hello
From: https://www.cnblogs.com/REN-Murphy/p/17805924.html

相关文章

  • 搓一个Pythonic list
      总所周知,Python语言当中的list是可以存储不同类型的元素的,对应到现代C++当中,可以用std::variant或者std::any实现类似的功能。而Python官方的实现当中用到了二级指针,不过抛开这些,我们也可以自己设计一个list的架构,实现多类型值的存储容器。  下图是自己实现的list的架构,按......
  • 详解Java LinkedList
    LinkedList简介LinkedList是List接口的实现类,基于双向链表实现,继承自AbstractSequentialList类,同时也实现了Cloneable、Serializable接口。此外还实现了Queue和Deque接口,可以作为队列或双端队列使用。LinkedList的插入删除时间复杂度:在头部或尾部插入删除元素,只需要修改头节......
  • Intrepid—总线采集测试仿真工具
    产品概述    VehicleSpy是英特佩斯推出的简单易用的高性价比总线工具,包含分析软件和采集调试硬件,具备对各类总线数据的网络监控、诊断、总线分析、数据采集、节点仿真、自动化测试等功能,目前支持的总线类型包含CAN、CANFD、LIN、FlexRay、车载以太网等各类总线格式。 ......
  • Java踩坑之List的removeAll方法
    最近写个功能,需要用到差集,然后就想到了javaList中有一个removeAll方法,正好可以实现差集功能,可以直接调用。我们知道,apache的common-collections包下面得CollectionUtils.subtract()方法也可以对List作差集,为了比较两种方式差集的结果,见Java中CollectionUtils.subtract()......
  • flask模版中使用全局变量
     fromflaskimportFlaskapp=Flask(__name__)@app.context_processordefinject_global_variables():return{'site_name':'MyWebsite'}@app.route('/')defindex():returnrender_template('index.html')......
  • http包中的ListenAndServe函数是阻塞式的
    packagemainimport( "fmt" "net/http")funcmain(){ fmt.Println("beforelisten") http.ListenAndServe(":1000",nil) fmt.Println("afterlisten")}执行结果为了避免ListenAndServe函数因监听端口而阻塞后面流程,需要开协程来执行该函数......
  • c# list集合克隆
    在C#中,List集合是一种泛型集合,可以存储任何类型的对象。克隆一个List集合可以通过以下几种方式实现:使用List的构造函数使用List的构造函数可以创建一个新的List对象,并将原始List中的元素复制到新List中。例如:List<int>list1=newList<int>{1,2,3};......
  • nginx 全局变量记录
    remote_addr客户端ip,如:192.168.4.2binary_remote_addr客户端ip(二进制)remote_port客户端port,如:50472remote_user已经经过AuthBasicModule验证的用户名host请求主机头字段,否则为服务器名称,如:dwz.stamhe.comrequest用户请求信息,如:GET/?_a=index&_m=show&count=10HT......
  • 详解Java ArrayList
    ArrayList简介ArrayList是List接口的实现类,底层基于数组实现,容量可根据需要动态增加,相当于动态数组。ArrayList继承于AbstractList,并且还实现了Cloneable、Serializable、RandomAccess接口。List:表明是列表数据结构,可以通过下标对元素进行添加删除或查找。Serializable:表示可......
  • arrrayList扩容机制
    扩容机制1.最小扩容=原数组长度+1;2.新容量=老容量+老容量/23.若新容量<最小扩容新容量=最小容量4.若新容量>最大容量(2的23次方-1-8)新容量=最小扩容>最大容量?最大值(2的23次方-1):最大容量......