[Vuejs]-Undefined while getting array element by index written in the variable in Vue.JS

0👍

Your best bet is to move the currentStep to a computed property. Also, steps need to exist in data so they are reactive:

let steps = ['Handler', 'Categories', 'Finalize'];
export default {
    components: {
        Handler,
        Categories,
        Finalize
    },

    data() {
        return {
            step: 0,
            steps,
        }
    },
    computed: {
      currentStep() {
        return this.steps[this.step];
      }
    }
}

If possible, prefer to stick the steps directly in data:

data() {
    return {
        step: 0,
        steps: ['Handler', 'Categories', 'Finalize'];,
    }
},

(But that may not be possible if you’re importing them from the outside. I don’t know about your specific use case).

In general, in Vue, when something directly depends on the value of some component properties, computed properties are the way to go: they are performant and clear.

In your original code, should it have worked, currentStep would not react to a change in step. Using a computed property, instead, whenever the step updates, the currentStep will update accordingly.

Leave a comment