Skip to content
Advertisement

Why is this error not letting me async render Vue Components?

I’m quite new with Vue, and I’m trying to lazy load a Component, I’m getting this error which I don’t understand, there should probably be a syntax error. Here’s the code:

<template>
    <div class="container">
    <h1>Async testing</h1>
    <button @click="showModal=!showModal">show modal</button>
    <Modal v-if=showModal />
    </div>
    
</template>

<script>

import { defineAsyncComponent, ref } from 'vue';
    export default {
        components: {
          Modal: () => defineAsyncComponent(
            () => import('@/components/Modal.vue')
          )
        },
        setup(){
            const showModal = ref(false);
            return {
                showModal
            }
        }
    }
    
</script>

The Modal Comp is just a simple h2 and a p with a red border (I already tried the same code without lazy load, and it works fine). Here’s the error: enter image description here

Advertisement

Answer

By wrapping defineAsyncComponent() in a function, you’re incorrectly declaring the Modal component as a function:

export default {
  components: {
        /* 👇 don't do this */
    Modal: () => defineAsyncComponent(() => import('@/components/Modal.vue'))
  },
}

The simplest solution is to remove the function wrapper:

export default {
  components: {
    Modal: defineAsyncComponent(() => import('@/components/Modal.vue'))
  },
}

demo

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement