Skip to main content

Command Palette

Search for a command to run...

Vue中组件间传值

Published
1 min readView as Markdown

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

child1.vue

<!-- 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>
<!-- 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>

More from this blog

EddieQiao's blog

84 posts

coder, work in suzhou