DEV Community

Advanced Vue: Controlling Parent Slots (Case Study)

Michael Thiessen on August 16, 2019

Let me ask you about something you've probably never thought about: Is there a way to populate a parent's slot from a child component? Recently...
Collapse
 
anduser96 profile image
Andrei Gatej

Interesting problem!

I’d use vm.$root.$on and vm.$root.$emit to be able to control a component from outside.

<template>
  <div>
    <FullPageError />
    <component :is=“crtActionBar” /> 
    <App />
  </div>
</template>

<script>
export default {
 data: () => ({
    crtActionBarName: action1,
  }),

 computed: {
   crtActionBar () {
     return () => import(`path/to/dir/actionBars/${this.crtActionBarName}`)
  }
 },

  created () {
    this.$root.$on(changeActionBar, actionBarName => {
      this.crtActionBarName = actionBarName;
   })
  }
}

</script>

Now from your child component, where you want to change parent’s data from.

created () {
   this.$root.$emit(changeActionBar, action2);
 }