Reputation: 93
Imagine I have a order form with 3 stages - Personal details, Order details, payment.
I want to toggle the next component from within the previous one (hoping to adjust the value of 'step')
<Component1 v-if="step = 1"></Component1>
<Component2 v-else-if="step = 2"></Component2>
<Component3 v-else></Component3>
So, with those on my view, is it possible for me to pass the value of 'step' in to component1 and do something like
<button v-on:click="step = 2">
Submit
</button>
then on that click, update the value of step on my main view (with the 3 components) and with that, hide my first completed component and displaying the second?
Thanks for any insight!
Upvotes: 1
Views: 4395
Reputation: 1
If you are still searching for the answer. This first code to add as your parent component.
<template>
<main>
<component @nextStep="changeStep" v-bind:is="selectedComponent"></component>
</main>
</template>
<script lang="ts">
import Setup1 from '@/components/Setup/Setup1.vue';
import Setup2 from '@/components/Setup/Setup2.vue';
import Setup3 from '@/components/Setup/Setup3.vue';
export default {
name: "SetupView",
components: {
Setup1, Setup2, Setup3
},
data() {
return {
selectedComponent: "Setup1"
}
}, methods: {
changeStep(step: string) {
this.selectedComponent = step;
}
},
}
</script>
Add the code below as the child component .
<template>
<div>
Setup step 1
<button @click="changeStep">Next step</button>
</div>
</template>
<script lang="ts">
export default {
name: "setup1",
methods: {
changeStep() {
this.$emit("nextStep", "Setup2");
}
}
}
</script>
v-bind:is="selectedComponent"
Upvotes: 0
Reputation: 14904
Why you dont use dynamic components?
On your parent component you listen to the event that changes yours step, i named it here nextStep
. This event triggers the method changeStep
that changes the component name.
<component @nextStep="changeStep" :name="selectedComponent"></component>
import component1 from "../components/component1.vue";
import component2 from "../components/component2.vue";
import component3 from "../components/component3.vue";
export default {
data(){
return {
selectedComponent: "component1"
}
}
},
methods: {
changeStep(step){
this.selectedComponent = step;
}
},
components: {
component1,
component2,
component3
}
//in the child component
method: {
changeStep(){
this.$emit("nextStep", "component2");
}
}
This is how you emit the event to the parent to change the component
You just need to change the property selectedComponent
to the component name you want and it will change it
Upvotes: 5