user14166158
user14166158

Reputation:

Vue - how to pass array in this case?

This is my sample code. I wanted to create a small form builder.

I will have many select fields. How can I pass an array into a loop? My code doesn't work, but I hope you know what effect I want to get.

<template>
    <div>
        <div v-for="(input, index) in formBuilder" :key="index">
            <h1>{{ input.name }}</h1>
            <div>
                Options:<br />
                {{ formBuilder.options }}
            </div>
        </div>
    </div>
</template>

<script>
import { mapState } from "vuex";

export default {
    data() {
        return {
            formBuilder: [
                {
                    name: "Name",
                    options: this.versions,
                },
                {
                    name: "Host",
                    options: this.countryList,
                },
            ],
        };
    },

    computed: mapState(["versions", "countryList"]),
};
</script>

EDIT. Below, I have added a version that works. But can it be done in a better way? And is this the correct way?

It works:

<template>
    <div>
        <div v-for="(input, index) in formBuilder" :key="index">
            <h1>{{ input.name }}</h1>
            <div>
                Options:<br />
                {{ input.options }}
            </div>
        </div>
    </div>
</template>

<script>
import { mapState } from "vuex";

export default {
    data() {
        return {
            formBuilder: [
                {
                    name: "Name",
                    options: [],
                },
                {
                    name: "Host",
                    options: [],
                },
            ],
        };
    },

    created() {
        this.formBuilder[0].options = this.versions;
        this.formBuilder[1].options = this.countryList;
    },

    computed: mapState(["versions", "countryList"]),
};
</script>

Upvotes: 2

Views: 98

Answers (1)

Chop TRAN
Chop TRAN

Reputation: 529

As https://stackoverflow.com/users/381282/michal-lev%c3%bd mention. computed property is your "correct solution".

computed: {
  ...mapState(['versions', 'countryList']),
  formBuilder() {
    return [
      { name: "Name", options: this.versions },
      { name: "Host", options: this.countryList },
    ]
  }
}

Explaination:

  • If you put the code in created it will only prepare formBuilder once when the component created.
  • If you use computed the formBuilder will be recomputed everytime this.versions or this.coutryList get updated.

Upvotes: 1

Related Questions