Search code examples
vue.jsquasar

How to import a component as prop from another component?


It is possible to import a component as prop from another component?

For example:

Q-Dialog

 <template>
  <q-dialog>       
    <q-layout>
        <q-page-container>
        
          <myCustomComponent />

      </q-page-container>
    </q-layout>
  </q-dialog>
</template>

<script>    
//Edited:This works, but I want to register dynamically from props
//import myCustomComponent from "components/MyCustomComponent.vue";

import myCustomComponent from this.myComponent;
    
export default {  
  props: ["myComponent"],
  components: { myCustomComponent }
}

Another component:

this.$q.dialog({
    component: CustomComponent, //dialog
    myComponent: 'components/MyCustomComponent.vue'
})

Edited, for better clarify what I am trying to achieve in this case:

My dialog is an abstract component in which an unlimited number of different myCustomComponent can be rendered.

To achieve this, I need that the registration of each component (import) is not done in the q-dialog.

A solution to consider is to register each component in the file from which the q-dialog is loaded for rendering (different from the q-dialog, in my case the another component file) and then pass that path from the imported file to the q-dialog, possibly as props.

Is this possible?

Edited with solution:

Parent component

<script>    
 import registeredComponent from "components/MyCustomComponent.vue";

 export default {
    data() {
      return {        
          myComponent: registeredComponent
      }
    }
        
  methods: {
      btnClickShowDialog(){
          this.$q.dialog({
              component: dialogComponent,
              //pass registered component as prop to dialog
              myCustomComponent: this.myComponent 
          })
      }   
  }
</script>

Q-dialog

<template>
  <q-dialog>       
    <q-layout>
        <q-page-container>
        
          <component :is="myCustomComponent" />

      </q-page-container>
    </q-layout>
  </q-dialog>
</template>

<script>        
    export default {  
      props: ["myCustomComponent"]
    }
</script>

Solution

  • In your q-dialog component you can use the component tag to dynamically render a passed in component prop. See this stackblitz.

    // q-dialog html
    <component :is="myComponent" />
    
    

    In your parent component you'll want to import the desired component, assign it to a data property and pass it in

    // parent component js
    import SomeComponent from './SomeComponent.vue'
    
    data () {
        return {
            passedInComponent: SomeComponent
        }
    
    }
    
    // parent component html
    <q-dialog :my-component="passedInComponent" />