Skip to content

Instantly share code, notes, and snippets.

@CDT
Last active October 28, 2022 01:11
Vue component communication
<!--Parent-->
<template>
<child-component @eventFromChild="handleChildEvent" />
</template>
<script>
export default {
name: 'ParentComponent',
methods: {
handleChildEvent(arg1, arg2, arg3) {
console.log('handle child event', arg1, arg2, arg3)
}
},
components: { ChildComponent }
}
</script>
<!--Child-->
<template />
<script>
export default {
name: 'ChildComponent',
methods: {
sendMessageToParent () {
this.$emit('eventFromChild', arg1, arg2, arg3) // and so on
}
}
}
</script>
<!--ComponentA-->
<template />
<script>
export default {
name: 'ComponentA',
methods: {
sendMessage () {
this.$root.$emit('EventFromA', arg1, arg2)
}
}
}
</script>
<!--ComponentB-->
<template />
<script>
export default {
name: 'ComponentB',
mounted () {
this.$root.$on('EventFromA', (arg1, arg2) => {
console.log('event from A: ', arg1, arg2)
})
},
beforeDestroy () {
this.$root.$off('EventFromA') // To unsubscribe all EventFromA
}
}
</script>
<script>
// https://stackoverflow.com/questions/55297461/vue-this-root-off-unsubscribes-all-instances-of-the-component-from-the-glob
let handler = (arg1, arg2) => {
console.log('event from A: ', arg1, arg2)
}
export default {
name: 'ComponentB',
mounted () {
this.$root.$on('EventFromA', handler)
},
beforeDestroy () {
this.$root.$off('EventFromA', handler) // To unsubscribe specific listener
}
}
</script>
<!--Parent-->
<template>
<child-component message="Hi" /> <!-- For static content -->
<child-component :message="msg" /> <!-- For dynamic content -->
</template>
<script>
export default {
name: 'ParentComponent',
data () {
return {
msg: 'Hi'
}
},
components: { ChildComponent }
}
</script>
<!--Child-->
<template>
<h1>{{ message }}</h1>
</template>
<script>
export default {
name: 'ChildComponent',
props: {
message: String
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment