# Vue中组件间传值

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1678333704287/c818b651-1ff2-407e-aa73-379d37c08e89.png align="center")

获取到一个 vue 实例，一个实例`$on`方法监听，一个实例$emit触发事件。两个兄弟组件的父组件是$parent，非兄弟组件间消息传递可以用$root根组件。

child1.vue

```xml
<!-- child1.vue -->
<template>
<div class="child1">
  
</div>
</template>
<script>
export default {
  mounted () {
    // this.$bus.$on('apply', (...arg) => {
    //   console.log(arg)
    // })

    // this.$parent.$on('apply', (...arg) => {
    //   console.log(arg)
    // })
    this.$root.$on('apply', (...arg) => {
      console.log(arg)
    })
  },
}
</script>
```

```xml
<!-- child2.vue -->
<template>
<div class="child2">
  <button @click="emitEvent">给child1发事件</button>
</div>
</template>
<script>
export default {
  methods: {
    emitEvent () {
      // 方法1，bus模式
      // this.$bus.$emit("apply", 132)
      // 方法2
      this.$parent.$emit("apply", 'parent')
      // 兄弟组件间事件传递用$parent。非兄弟组件间事件传递可以用$root
      this.$root.$emit("apply", 'parent')
    }
  }
}
</script>
```
