Home » vue » Array of Vue Components Changed by a Counter

Array of Vue Components Changed by a Counter

Posted by: admin November 26, 2021 Leave a comment

Questions:

I have a view that will have a section with components that are already built. I want to take that information captured in each component and put it into a json object. The view looks like this:

<template>
  <v-row>
    <v-flex>
      <v-btn 
        :click="prevStep"
        v-if="counter != 0"
      >
        Back
      </v-btn>
      <v-btn 
        :click="nextStep"
        v-if="counter != component.length"
      >
        Next
      </v-btn>
      <keep-alive>
      <component :is="component[counter]"></component>
      </keep-alive>
      <v-btn 
        :click="submit" 
        v-if="counter == component.length"
      >
        Submit
      </v-btn>
...
</template>

<script>
import ALL THE COMPONENTS (3 total)

export default {
  name: "formSubmit",
  components: {
    comp1,
    comp2,
    comp3
  },
  
  data() {
    return {
      component: [
        'comp1',
        'comp2',
        'comp3'
      ],

      counter: 0,
    }
  },

  methods: {
    nextStep: function() {
      this.counter++;
    },

    prevStep: function() {
      this.counter--;
    }
  }
}
</script>

So if I hardcode counter to the correct array slot, it loads that component like I expect, but clicking my buttons does nothing and does not change which component is active. I have tried adding a console.log to each button method to display the current value of the counter, but nothing shows up – no entry in the console for counter at all.

Am I over-complicating this or have I just made a dumb error somewhere?

Answers:

You use click like a prop and not like an event. Replace both :click with @click:

<v-btn 
        @click="prevStep"
        v-if="counter != 0"
      >

<v-btn 
        @click="nextStep"
        v-if="counter != component.length"
      >