Vue---全局事件总线(实现任意组件间通信)

红太狼 2024-04-07 15:35 179阅读 0赞

目录

总结

一、实现

main.js

重要代码:

school.vue

重要代码

student.vue

重要代码


总结

69181b85f2ac48fbbf2e71f34f38ef1d.png

一、实现

案例:由student.vue 向school.vue传输数据 其两文件之间的关系是兄弟关系

main.js

  1. // 该文件是整个项目的入口文件
  2. // 引入vue,这个vue不能解析template配置项
  3. import Vue from 'vue'
  4. // 下面这个是引入完整版的vue。这个vue能解析template配置项
  5. // import Vue from 'vue/dis/vue'
  6. // 引入APP组件,它是所有组件的父组件
  7. import App from './App.vue'
  8. Vue.prototype.x={a:10}
  9. // 关闭vue的生产提示
  10. Vue.config.productionTip = false
  11. // 创建vue实例对象---vm
  12. new Vue({
  13. el:'#app',
  14. render: h => h(App),
  15. //这个里面的this是vm 此时模板还没有解析
  16. beforeCreate(){
  17. // Vue.prototype在原型上定义
  18. // 这个地方为什么不写等于vm? 因为当这个new Vue执行完成之后才有vm 我们现在还是在new vm中
  19. // 安装全局事件总线
  20. Vue.prototype.$bus = this
  21. }
  22. })

重要代码:

  1. //这个里面的this是vm 此时模板还没有解析
  2. beforeCreate(){
  3. // Vue.prototype在原型上定义
  4. // 这个地方为什么不写等于vm? 因为当这个new Vue执行完成之后才有vm 我们现在还是在new vm中
  5. // 安装全局事件总线
  6. Vue.prototype.$bus = this
  7. }

school.vue

  1. <template>
  2. <div class="school">
  3. <h2> 学校名称:{
  4. {name}}</h2>
  5. <h2> 学校地址:{
  6. {address}}</h2>
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. name:'School',
  12. data(){
  13. return{
  14. name:'尚硅谷',
  15. address:'北京昌平',
  16. }
  17. },
  18. mounted(){
  19. this.$bus.$on('hello',(data)=>{
  20. console.log('我是School组件,收到了数据',data)
  21. })
  22. },
  23. beforeDestroy(){
  24. this.$bus.$off('hello')
  25. }
  26. }
  27. </script>
  28. <style scoped>
  29. .school{
  30. background-color: skyblue;
  31. padding:5px;
  32. margin-top:30px;
  33. }
  34. </style>

重要代码

  1. mounted(){
  2. this.$bus.$on('hello',(data)=>{
  3. console.log('我是School组件,收到了数据',data)
  4. })
  5. },
  6. beforeDestroy(){
  7. this.$bus.$off('hello')
  8. }

student.vue

  1. <template>
  2. <!-- <template>标签不参与编译,在页面展现的是下面的一段结构 -->
  3. <!-- 组件结构 -->
  4. <div class="student">
  5. <h2 > 学生名称:{
  6. {name}}</h2>
  7. <h2> 学生性别:{
  8. {sex}}</h2>
  9. <button @click="sendStudentName">把学生名给School组件</button>
  10. </div>
  11. </template>
  12. <script>
  13. export default {
  14. name:'Student',
  15. data(){
  16. return{
  17. name:'张三',
  18. sex:'男',
  19. age:18
  20. }
  21. },
  22. methods:{
  23. sendStudentName(){
  24. this.$bus.$emit('hello',this.name)
  25. }
  26. }
  27. }
  28. </script>
  29. <style scoped>
  30. .student{
  31. background-color: red;
  32. padding:5px;
  33. margin-top:30px;
  34. }
  35. </style>

重要代码

  1. <button @click="sendStudentName">把学生名给School组件</button>
  2. methods:{
  3. sendStudentName(){
  4. this.$bus.$emit('hello',this.name)
  5. }
  6. }

发表评论

表情:
评论列表 (有 0 条评论,179人围观)

还没有评论,来说两句吧...

相关阅读