我有一个Banner组件,它显示了基于道具的不同图像,例如,一个由3-4个横幅组成的页面将如下所示:
<Banner type="wide"></Banner>
<Banner type="small"></Banner>
<Banner type="medium"></Banner>当user单击横幅时,我需要将事件传播到该页面上出现的所有兄弟组件。所以在本例中是一个Banner组件。
但它毕竟是幕后的同一个组件,已经是mounted了。
如何在这种情况下共享传播数据?
发布于 2019-10-14 23:01:44
您可以使用emit
使用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存储,则需要更多的人工操作
https://stackoverflow.com/questions/58379248
复制相似问题