Home > Enterprise >  How to dynamically render vuejs components in an astro page using a global variable?
How to dynamically render vuejs components in an astro page using a global variable?

Time:01-11

I'm developing a form in several steps on Astro. For that I use Vuejs components (one for each step).

Each step can be validated by a button that allows to go to the next one. I tried to create a global variable that increments at each step via the button. Depending on the value of this variable the corresponding component should be displayed. Currently the value of the variable is updated by a function but the new value is not taken into account in the index.astro

The global variable :

export let newValue = 0
export function nextComponent(num){
    newValue = num  
}

my index.astro :

---
import Layout from "../layouts/Layout.astro";
import Vehicule from "../components/vehicule/vehicule.vue";
import Owner from "../components/vehicule/owner.vue";
import Informations from "../components/vehicule/informations.vue";
import Header from "../components/header.vue";

import {newValue} from "../assets/js/globalVariable.js"

---

<Layout title="Welcome to Astro.">
    <main>
        
        <Header client:load />
        {newValue === 0 && <Vehicule client:load />}
        {newValue === 1 && <Owner client:load />}
        {newValue === 2 && <Informations client:load />}
        
    </main>
</Layout>

CodePudding user response:

The best way is to probably move all these Vue components inside a single wrapper Vue component so that you can take advantage of Vue’s ways of handling interactivity.

index.astro might look something like this with a single hydrated <Steps /> component:

---
import Layout from "../layouts/Layout.astro";
import Header from "../components/header.vue";
import Steps from "../components/vehicule/steps.vue";
---

<Layout title="Welcome to Astro.">
    <main>
        <Header client:load />
        <Steps client:load />
    </main>
</Layout>

You would then use the vehicule, owner, and informations components inside this single steps manager.

  • Related