javascriptvue.jsinjectemitmulti-step

Multistep form vue


**I'm trying to reform a multistep form, but my first step and second step are visualised both at the same time now. Even though my app data is having an activePhase data stored. It seem like I should be using as a method some emit logic? Or as I'm usin Provide/Inject I should use Reactivity as here - https://vuejs.org/guide/components/provide-inject.html#working-with-reactivity ?

See the link please - https://codesandbox.io/s/intelligent-jasper-teh1im?file=/src/components/Step2.vue**

<template v-if="activePhase == 2">
  <div class="container">
    <div class="content-wrapper">
      <h1>Step 1</h1>
      <div class="form-group">
        <label>Payment Amount</label
        ><input
          name="paymentAmount"
          v-model="paymentAmount"
          placeholder="Your payment amount"
          class="form-control"
        />
      </div>
      <div class="form-group">
        <label>Account Number</label
        ><input
          name="accountNumber"
          v-model="accountNumber"
          placeholder="Your account number"
          class="form-control"
        />
      </div>
      <button type="button" @click.prevent="goToStep(3)" class="btn">
        Continue
      </button>
    </div>
    <Button />
  </div>
</template>

<script>
import Button from "./Button.vue";
export default {
  components: {
    Button,
  },
  inject: ["activePhase", "paymentAmount", "accountNumber"],
  methods: {
    goToStep(step) {
      this.activePhase = step;
    },
  },
};
</script>

<style>
</style>


Solution

  • I'd suggest to use dynamic components for this use case.

    So that your form accept 1 child, which will change overtime.

    <template>
      <Form>
        <component :is="currentStep" />
      </Form>
    </template>
    
    <script>
    import Step1 from './Step1.vue'
    import Step2 from './Step2.vue'
    
    export default {
      data() {
        return {
          steps: [Step1, Step2],
          stepIndex: 0,
        }
      },
      methods {
        nextStep() {
          this.stepIndex++
        }
      },
      computed {
        currentStep() {
          return this.steps[this.stepIndex]
        }
      }
    }
    </script>