淘特app官方网站下载,公司做网站 需要准备什么,php网站怎么做后台管理,seo推广优化培训组件间通信方式是前端必不可少的知识点#xff0c;前端开发经常会遇到组件间通信的情况#xff0c;而且也是前端开发面试常问的知识点之一。接下来开始组件间通信方式第三弹------$bus,并讲讲分别在Vue2、Vue3中的表现。 Vue2Vue3组件间通信方式汇总#xff08;1#xff09… 组件间通信方式是前端必不可少的知识点前端开发经常会遇到组件间通信的情况而且也是前端开发面试常问的知识点之一。接下来开始组件间通信方式第三弹------$bus,并讲讲分别在Vue2、Vue3中的表现。 Vue2Vue3组件间通信方式汇总1------props Vue2Vue3组件间通信方式汇总2------$emit 一、全局总线$bus 原型链 归根结底就是在vmvue原型链上注册一个名叫$bus 的对象再把this就是vm实例对象赋给$bus其中$on $emit $off等就是全局可以读可写的变量,即可实现相关组件、不相关组件之间数组地传递。 ------Vue2
main.js文件中Vue实例下往Vue原型链上注册属性$bus
//引入Vue
import Vue from vue
//引入App
import App from ./App.vue
//关闭Vue的生产提示
Vue.config.productionTip false//创建vm
new Vue({el:#app,render: h h(App),beforeCreate() {Vue.prototype.$bus this//注册全局事件总线}
})
其中一个组件调用全局总线的$emit
templatediv classstudenth2学生姓名{{name}}/h2h2学生性别{{sex}}/h2button clicksendStudentName把学生名给另一个组件/button/div
/templatescriptexport default {name:Student,data() {return {name:张三,sex:男,}},methods:{sendStudentName(){this.$bus.$emit(hello,this.name)}}}
/scriptstyle scoped.student{background-color: pink;padding: 5px;margin-top: 30px;}
/style 另一个组件调用全局总线的$on
templatediv classschoolh2学校名称{{name}}/h2h2学校地址{{address}}/h2/div
/templatescriptexport default {name:School,data() {return {name:学校名,address:学校地址,}},mounted() {this.$bus.$on(hello,(data) { //绑定自定义事件hello并留下回调函数console.log(我收到了data);})},beforeDestroy() {this.$bus.$off(hello) },}
/scriptstyle scoped.school{background-color: skyblue;padding: 5px;}
/style------Vue3 不存在vm所以需要引入mitt插件 npm install mitt 在bus.ts文件中引入
import mitt from mitt
//mitt是一个函数赋给命名为$bus的变量
const $busmitt();
//向外暴露这个变量
export default $bus 其中一个组件
使用mitt中的$emit函数,向$on传输数据,第一个参数是和$on第一个参数向对应的字段名,余下的参数是要传输的数据,和Vue实例对象上的$emit,$on用法差不多.
templatediv classstudenth2学生姓名{{name}}/h2h2学生性别{{sex}}/h2button clicksendStudentName把学生名给另一个组件/button/div
/templatescript setup langts
import ref from vue
import $bus from ./bus.ts
let nameref(张三)
let sexref(男)
let sendStudentName(name.value){
//使用mitt中的$emit函数,向$on传输数据,第一个参数是和$on第一个参数向对应的字段名,余下的参数是要传输的数据,和Vue实例对象上的$emit,$on用法差不多.$bus.$emit(hello,name.value)
}
/scriptstyle scoped.student{background-color: pink;padding: 5px;margin-top: 30px;}
/style 另一个组件$on接收数据
templatediv classstudenth2学生姓名{{name}}/h2h2学生性别{{sex}}/h2button clicksendStudentName把学生名给另一个组件/button/div
/templatescript setup langts
import {refonMounted) from vue
import $bus from ./bus.ts
let nameref(张三)
let sexref(男)
onMounted((){$bus.$on(hello,(data){name.valuedata})})/scriptstyle scoped.student{background-color: pink;padding: 5px;margin-top: 30px;}
/style