首页 > 解决方案 > 将事件从一个组件传递到其他组件

问题描述

我对 Vue 真的很陌生,似乎无法了解事件是如何从一个组件传递到其他组件的。我目前正在使用v-blur,我想模糊除单击的组件之外的每个组件。我想通过在单击原始组件时将事件传递给其他组件,我可以获得想要的效果。任何帮助深表感谢!

// Parent.vue
<template>
  <div id="Parent">
    <child-one @toggle-blur="toggleChildBlur"/>
    <child-two @toggle-blur="toggleChildBlur"/>
    <child-three @toggle-blur="toggleChildBlur"/>
  </div>
</template>

<script>
import ChildOne from './ChildOne'
import ChildTwo from './ChildTwo'
import ChildThree from './ChildThree'

export default {
  name: 'Parent',
  components: {
    ChildOne, ChildTwo, ChildThree
  },
  methods: {
    toggleChildBlur () {
      // Blur every child except the clicked one?
    }
  },
  data () {
    return {}
  }
}
</script>  

// ChildOne.vue, basically the same for two and three aswell
<template>
  <div id="child-one" v-blur="blurConfig" @click="$emit('toggle-blur')"></div>
</template>

<script>
export default {
  name: 'ChildOne',
  methods: {
    toggleBlur () {
      this.blurConfig.isBlurred = !this.blurConfig.isBlurred;
    }
  },
  data () {
    return {
      blurConfig: {
        isBlurred: false,
        opacity: 0.3,
        filter: 'blur(1.2px)',
        transition: 'all .3s linear'
      }
    }
  }
}
</script>

标签: vue.jsvuejs2

解决方案


在 Vue 中调度的事件向一个方向传播:子 ⇒ 父。如果你有一个组件 P(父)和子 C1(子 1)和 C2(子 2),则无法在 C1 中触发事件并将其发送到 C2。它会去P。

如果您有非常嵌套的结构(许多级别)并且您确实需要这样做,那么最简单的方法是调度和侦听不属于显示列表一部分的事件,即全局事件。非常典型的解决方案是拥有所谓的“事件总线”——一个单独的虚拟 Vue 实例,仅用于事件。这是关于Vue 中的全局事件总线的完整教程。

它看起来像这样:

// in some global file
const EventBus = new Vue();

// in GC1 (parent -> child 1 -> grand child 1)
EventBus.$emit('someEvent', 'some-data')

// in GC5 (parent -> child 3 -> grand child 5)
EventBus.$on('someEvent', function(data) {
  console.log(data) // 'some-data
})

通过这种方式,您可以轻松地在整个地方分发/捕获事件。

祝你好运!:)


推荐阅读