Home > Web Front-end > JS Tutorial > Introduction to the use of value transfer and event bus (eventbus) in Vue non-parent-child components

Introduction to the use of value transfer and event bus (eventbus) in Vue non-parent-child components

不言
Release: 2019-01-10 09:28:36
forward
2470 people have browsed it

This article brings you an introduction to the use of value transfer and event bus (eventbus) in Vue non-parent-child components. It has certain reference value. Friends in need can refer to it. , hope it helps you.

Let’s first talk about what an event bus is. It is actually a subscription publisher model;

For example, there is a bus object. There are two methods on this object, one is on (listening, That is, subscription), one is emit (trigger, that is, publishing), we listen to an event through the on method, then use emit to trigger the event, and at the same time call the callback function in on, thus completing an event trigger;

This is a design pattern that has nothing to do with language;

If you don’t know what the subscription publisher pattern is, please read this article JavaScript design pattern--observer pattern (Publisher-Subscriber Model)

In actual development, the most troublesome thing is often the value transfer problem between various components; if you use the event bus, this matter will become very simple;

The shortcomings of vue’s own event bus

We all know that after vue is instantiated, it has the ability to act as an event bus object. Hang on it There are two methods, $emit and $on;

The vue document makes it very clear that $emit will trigger events on the current instance, and additional parameters will be passed to the listener callback;

Since in actual work, we develop in the form of components, and each component is an instance;

There are great limitations in using the bus capabilities of vue. At most, it can only be developed from sub-components. Triggered to the parent component, but cannot pass values ​​between non-parent and child components;

So at this time, we need to have a global event bus object, allowing us to mount listening events and triggering events;

For example, a child component passes a value to a parent component; it is very simple for a parent component to pass a value to a child component. We will not talk about here
// 子组件中
<template>
  <div>
    <span>{{child}}</span>
    <input type="button" value="点击触发" @click="send">
  </div>
</template>
<script>
  export default {
    data () {
      return {
        child: '我是子组件的数据'
      }
    },
    methods: {
      send () {
      // 如果传多个值就用逗号隔开 a, b, c
        this.$emit('fromChild', this.child)
      }
    }
  }
</script>
Copy after login
// 父组件
<template>
  <div>
    <span>{{name}}</span>
    // 在父组件中监听 fromChild事件
    <child @fromChild="onFromChild"></child>
  </div>
</template>
<script>
  import child from './child'
  export default {
    components: {
      child
    },
    data () {
      return {
        name: ''
      }
    },
    methods: {
      onFromChild: function (data) {
        // data就是子组件传过来的值
        // 如果传过来多个值就用逗号隔开去接收 data1, data2, data3
        this.name = data
      }
    }
  }
</script>
Copy after login

Several ways to implement global event bus objects

Method 1 is also the method I use myself (recommended, simple)

The general idea is: in main.js, which is the entry file, we are on the prototype of vue Add a bus object;

The specific implementation method is as follows:

The following component A and component B can be any two components in the project

//在mian.js中
Vue.prototype.bus = new Vue()  //这样我们就实现了全局的事件总线对象

//组件A中,监听事件
this.bus.$on('updata', function(data) {
    console.log(data)  //data就是触发updata事件带过来的数据
})

//组件B中,触发事件
this.bus.$emit('updata', data)  //data就是触发updata事件要带走的数据
Copy after login

The second method is a little troublesome, but it is also easy to understand the general implementation idea: Create a new bus.js file and instantiate vue in this file; then introduce this in component A and component B respectively. bus.js file, hang event monitoring and event triggering on the bus.js instance, so that global monitoring and triggering can be achieved

Write an example

bus.js file
// bus.js文件
import Vue from 'vue'
export default new Vue()
Copy after login
Component A
// 组件A ,监听事件send
<template>
  <div>
    <span>{{name}}</span>
  </div>
</template>
<script>
  import Bus from './bus.js'
  export default {
    data () {
      return {
        name: ''
      }
    },
    created() {
      let _this = this
      // 用$on监听事件并接受数据
      Bus.$on('send', (data) => {
        _this.name = data
        console.log(data)
      })
    },
    methods: {}
  }
</script>
Copy after login
Component B

// 组件B, 触发事件send
<template>
  <div>
    <input type="button" value="点击触发" @click="onClick">
  </div>
</template>
<script>
  import Bus from './bus.js'
  export default {
    data () {
      return {
        elValue: '我是B组件数据'
      }
    },
    methods: {
        // 发送数据
      onClick() {
        Bus.$emit('send', this.elValue)
      }
    }
  }
</script>
Copy after login
In this way we have completed a simple value transfer between non-parent and child components.

The above is the detailed content of Introduction to the use of value transfer and event bus (eventbus) in Vue non-parent-child components. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template