【问题标题】:Sibling Component communication of Same component同一组件的同级组件通信
【发布时间】:2020-02-11 05:22:53
【问题描述】:

我有一个 Banner 组件,它根据道具显示不同的图像,例如,由 3-4 个横幅组成的页面看起来像:

<Banner type="wide"></Banner>
<Banner type="small"></Banner>
<Banner type="medium"></Banner>

user 点击横幅时,我需要将事件传播到该页面上的所有同级组件。所以在这种情况下是一个Banner 组件。

但毕竟是mounted 的幕后组件。

在这种情况下如何共享传播数据?

【问题讨论】:

  • 这取决于您要完成的工作。横幅是否会因为其中一个被点击而改变状态?如果是这样,当其中一个发出“click”事件时,父母可能会向所有人传递一个道具。
  • @DavidWeldon:你的意思是孩子 -> 父母 -> 所有孩子的(广播)?
  • child 向 parent 发出一个点击事件 -> parent 改变状态以知道哪个孩子被点击了 -> parent 将最后一次点击的Banner 的 id/name/etc 传递给每个孩子。每个孩子都可以watch 更改最后点击的项目。

标签: javascript vue.js vuejs2 vue-component vuex


【解决方案1】:

你可以使用emit

使用发射是相当直接的

注意emit('myEmitEvent') 方法不会只针对兄弟组件,任何注册@myEmitEvent 的组件都会收到消息

<!-- Banner.vue -->
<!-- note that this is not working code, but a means to demonstrate -->
<!-- how to use the 'emit' method -->

<template>
    <app>
        <img @click="notify" @bannerEvent="subscribe"/>
    </app>
</template>

<script>
    export default {
        methods: {
            notify () {
                this.$emit('bannerEvent', somePayloadIfYouWant)
            },

            subscribe (payload) {
                console.log(payload)
            }
        }
    }
</script>

如果你正在使用 vuex 存储,你可以使用它进行更间接的通信,通过使用 computed 属性,但如果你不使用 vuex 存储,那就有点做作了

【讨论】:

    猜你喜欢
    • 2021-08-13
    • 2016-11-05
    • 2023-03-26
    • 2016-09-07
    • 1970-01-01
    • 2019-12-20
    • 2020-01-18
    • 2020-08-30
    • 2018-04-03
    相关资源
    最近更新 更多