DjSh
DjSh

Reputation: 2764

Circular References Between Components Vue

I have created two components (A and B). I am trying to make them recursive. So CompA calls ComB, CompB calls CompA and so on:

Page -> CompA -> CompB -> CompA -> CompB -> ...

This is my CompA.Vue

<CompB></CompB>

and its script:

import CompB from './CompB';
export default {
    name: "CompA",
    components:{CompB},
    props:['items']
 },
 beforeCreate() {
        this.$options.components.CompB = require("./CompB").default;
    },

and this is CompB.Vue:

<v-comp-a :items="test"></v-comp-a>

and its script:

 import CompA from '../components/CompA'
export default {
    name: "v-comp-b",
    components:{'v-comp-a':CompA},
    props: {
        label: {
            typ:String,
            required:true
        },
        properties:{
            type:Array,
            required:true
        }
    },

So, the main page loads with CompA and I can call CompB from there but the problem is that I cannot call CompA from CompB. I get this error: Unknown custom element:v-comp-a did you register the component correctly?

I have also imported both of the components in App.Vue:

import CompA from './components/CompA'
import CompB from './components/CompB'

and in script:

components: {
   CompA,
   CompB
}

and this is main page that passes data:

<v-comp-a :items="items"></v-comp-a>

I already saw this question. and read this documentation. I tried to show the import only since it would be very long, I also used CompA instead of v-comp-a. It did not help.

Please Help. I m starting to lose it :[

Upvotes: 4

Views: 7867

Answers (2)

Motla
Motla

Reputation: 1230

With Vue 3, you can use Async Components:

export default {
  name: "CompA",
  components: {
    "CompB": defineAsyncComponent(() => import('./CompB.vue'))
  }
}

Documentation:

Upvotes: 4

Ignace Vau
Ignace Vau

Reputation: 541

You have quite a lot of syntax errors: in CompA.vue:

  • beforeCreate() should be inside your export default
  • You are importing CompB in the beforeCreate hook, so remove the other import
  • Don't declare ComB in components
  • (There is still a comma after the last bracket but I guess that this is not the case in the actual project)

export default {
  name: "CompA",
  props:['items'],
  beforeCreate() {
    this.$options.components.CompB = require("./CompB.vue").default;
  }
}

Leave CompB.vue as it is and you should see the error disappear.

Now they are recursive but basically CompB is in CompA is in CompB ...
So making them recursive should give a recursive error.

Upvotes: 4

Related Questions