首页 > 其他分享 >Vue项目中使用中央事件总成进行参数传递

Vue项目中使用中央事件总成进行参数传递

时间:2023-02-03 19:22:22浏览次数:44  
标签:Vue text 参数传递 总成 export eventbus

Vue项目中使用中央事件总成进行参数传递

 

作用场景:当不使用VueX的情况下,且组件之间不存在父子关系,就可以使用到中央事件总成进行参数传递

 

步骤一:先是需要在 工具函数文件夹( untils ) 中创建一个相对应的函数文件

  • 路径 src / untils / eventbus.js

import Vue from "vue";
const eventBus = new Vue()

export default eventBus;

 

步骤二:在 main.js 中让 项目的原型链上的 $eventbus 绑定上我们声明的 eventbus 工具函数

....

import bus from "@/untils/eventbus";
Vue.prototype.$eventbus = bus

new Vue({ ...

 

步骤三:在 组件一 中声明需要传递的数据

<template>
   <div>
       <button @click="sendfn">点击进行传值</button>
   </div>
</template>

<script>
export default {
   data() {
       return {
           text: "小明乘坐火车已经抵达"
      }},
   methods: {
       sendfn() {
           this.$eventbus.$emit("send", this.text)
      }}
}
</script>

需要关注的语法点:

 this.$eventbus.$emit("自定义数据名称", 需要传递的数据 )

 

步骤四:在 组件二 中对已经声明的数据进行接收

<template>
   <div>
      child2 :{{ text }}
   </div>
</template>

<script>
export default {
   data() {
       return {
           text: "小明仍然在乘坐火车"
      }},
   mounted() {
       this.$eventbus.$on("send", (val) => {
           this.text = val
      })
  }}
</script>

需要关注的语法点:

this.$eventbus.$on("自定义数据名称", (val) => { 对接收到的数据进行处理的函数 })
  • 需要放在生命函数(此处使用 mounted )当中

标签:Vue,text,参数传递,总成,export,eventbus
From: https://www.cnblogs.com/Dollom/p/17090268.html

相关文章