[Vuejs]-How to reuse a first template inside a second div

0👍

I’d probably separate the form for each step into its own component. So for instance:

AddressForm.vue

<template>
  <div>
    <label>Address</label>
    <input type="text" v-model="localValue.address" />

    <label>City</label>
    <input type="text" v-model="localValue.city" />

    <label>State</label>
    <input type="text" v-model="localValue.state" />
  </div>
</template>

<script>
export default {
  props: {
    value: Object,
  },
  computed: {
    localValue: {
      get() { return this.value; },
      set(value) { this.$emit("input", value); },
    },
  },
};
</script>

And then just reuse this component for each step:

<div v-if="step === 1">

    <h1>Step One</h1>
    <h4>Address</h4>
    
    <AddressForm v-model="step1address />

    <button @click.prevent="next()">Next</button>

 </div>
<div v-if="step === 2">
    <h1>Step Two</h1>
    <h4>Address 2</h4>

    <AddressForm v-model="step2address />

    <button @click.prevent="next()">Next</button>
</div>

Here’s a running sample of the above:
https://codesandbox.io/s/tender-antonelli-2n4vb

0👍

new Vue({
  el: '#app',
  data() {
    return {
      stepTotal: 2,
      step: 1,
      
      address: null,
      city: null,
      state: null
    }
  },
  methods: {
    prev() {
      this.step--;
    },
    next() {
      this.step++;
    },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <template v-for="index of stepTotal">
    <div v-if="step === index" :key="index">
        <h1>Step {{index}}</h1>
        <h4>Address</h4>
        <label>Address</label>
        <input type="text" v-model="address">

        <label>City</label>
        <input type="text" v-model="city">

        <label>State</label>
        <input type="text" v-model="state">

        <br>
        <button v-if="index != 1" @click.prevent="prev()">Prev</button>
        <button v-if="index != stepTotal" @click.prevent="next()">Next</button>
     </div>
  </template>
</div>

Leave a comment