Dynamic import of component fails

Viewed 311

I'm trying to implement the recommendation of this article on component dynamic import:

Template:

<component :is="componentLoader" />

Script:

computed: {
  componentLoader () {
    const modalComponent = 'HeroBanner'
    return () => import(`@/components/template-ux/${modalComponent}.vue`)
  }
}

But I'm getting an error:

Cannot read property 'value' of null - Occurred while linting D:\projects\my-project\components\global\Modal.vue:41

What is causing this issue?

EDIT: line #41 is the line starting with return () => import...

2 Answers

It looks like the component that you are loading is missing some props maybe. You can pass you props dynamically like so:

<component :is="componentLoader.component" v-bind="componentLoader.props"/>
computed: {
  componentLoader () {
    return {
       component: () => import(`@/components/template-ux/${modalComponent}.vue`),
       props: {
           value: 'Something'
           foo: 'Foo'
       }
    }
  }
}

Depending on what's happening in your file, you sometimes cannot dynamically import a component. Let's say if you need some values right when rendering the template. Here, there is a case where you do try to access a value with .value on something not here yet.

Solution would be to import it the classic way, or to make some validations on the elements, for example modal?.inputText?.value thanks to optional chaining (working only in the <script> section btw).

Please show us the content of Modal.vue to see what is happening here.

Related