Search code examples
javascriptvue.jsvue-componentvuejs3vue-composition-api

dynamic component doesn't work as intended in vue 3


I need to dynamically show a success of fail component based on the result of the api call, this is my example:
SCRIPT

const loader = ref(true);
const resultPage = ref("");

this.getResult()
.then((response : boolean) => {
    response ? resultPage.value = 'success' : resultPage.value = 'fail';
})
.finally(() => {
    loader.value = false
})

TEMPLATE

<component
   v-if="!loader"
   :is="resultPage"
   :key="resultPage"
 />

The component i created in my project is Success.vue and Fail.vue (using composition API).
I simply imported them:

import Fail from "./result/Fail.vue";
import Success from "./result/Success.vue";

The value of my ref resultPage is 'success' or 'fail'.
I noticed that if importing the component normally works, this is the case:

<success v-if="!loader" />

Am i missing anything?


Solution

  • Ok after a while i decided to re-read the documentation and i found this little paragraph which i didn't read the first time :_)
    Registration is not required if you pass the component itself to is rather than its name, e.g. in < script setup >.

    Basically i modified my code like this

    const loader = ref(true);
    const resultPage = ref({});
    this.getResult()
    .then((response : boolean) => {
        resultPage.value = response ? Success : Fail;
    })
    .finally(() => {
        loader.value = false
    })
    

    I think this issue is also related to Vue component only shows up as <componentName> Tag and didnt gets rendered.

    I'll keep it here to avoid making another one like me lose 2 hours of time