2

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>
  • Use `input.options` instead of `formBuilder.options`: https://vuejs.org/v2/guide/list.html – str Oct 06 '20 at 08:30
  • 2
    Does this answer your question? [Use computed property in data in Vuejs](https://stackoverflow.com/questions/44318343/use-computed-property-in-data-in-vuejs) – Michal Levý Oct 06 '20 at 08:33
  • It was my mistake. I have already corrected it. I updated the post. This method works for me. But isn't there a better solution? And most of all: is this the correct solution? –  Oct 06 '20 at 08:49

1 Answers1

1

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.
Chop TRAN
  • 487
  • 4
  • 9