How can Vue handle passing an array in this scenario?

In my code snippet, I am attempting to build a simple form builder application. The goal is to include multiple select fields in the form.

I encountered a problem with passing an array into a loop. Despite my efforts, the code did not work as expected. However, I am hopeful that you can understand the desired outcome I am aiming for.

<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>

UPDATE. I have made modifications to provide a working version of the code. While it functions correctly now, I am curious if there is a more efficient approach. Is this method considered best practice?

The updated code:

<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>

Answer №1

According to , the computed property is the optimal solution.

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

Explanation:

  • If you place the code in the created hook, the formBuilder will only be prepared once when the component is created.
  • However, if you utilize the computed option, the formBuilder will be recalculated every time this.versions or this.coutryList are updated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When PHP echo of json_encode triggers an error, AJAX status 200 will be raised

Despite everything running smoothly in the program below, an AJAX error is triggered: javascript: var data = { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026f6742656f636b6e2c616d6f">[email protect ...

Steps to verify if a value is an integer:

Lately, I've been working on a "spinner" that increments and decrements a number by 1 each time. However, I'm struggling to add validation to the program so that it only accepts integers (no decimals). I've tried looking into NaN and parseVa ...

File reading and processing must be completed before attempting to write to a new file. This is a promise-related stipulation

Feeling completely lost and stuck in a rut. Promises seemed straightforward until I actually tried to implement them. Sharing my basic code here without any promise attempts for simplicity's sake. After taking a few months hiatus from this, I returned ...

ng-if directive does not show data in AngularJS

I have a dynamic collection of images and videos that I want to display one at a time. Specifically, when I click on an image ID, I want it to show the corresponding image, and when I click on a video ID, I want it to show the relevant video. Below is the ...

When two $scopes are updated simultaneously, it leads to the duplication of data

Here is the snippet of code I am working with: $scope.addToOrder = function(index) { var tempItem = $scope.item; if (tempItem[index].validate == true){ if (_.isEmpty($scope.item2) == true) { $scope.item2.push ...

When using v-for to render an array list fetched from AsyncData, an error is thrown: The virtual DOM tree rendered on the client-side does not match the one

For my application, I am utilizing Nuxt.js. On one of the pages, I am using AsyncData to fetch an array of data objects from my API asynchronously. These data objects are then rendered in my template using v-for. Everything is functioning properly until I ...

Exploring solutions for handling asynchronous issues with vue3-google-map

While working with a Vue library for managing Maps called vue3-google-map, I encountered an issue when trying to define certain polylines that would not allow me to select the center of the marked area: Here is my map template: <template> <Goo ...

The output generated by grunt-contrib-handlebars differs from that of the handlebars npm task

Looking for some help with a problem similar to the one mentioned in this Stack Overflow question. Since that question hasn't been answered yet, I decided to create my own post. I'm currently attempting to precompile my handlebars template files ...

Having trouble exporting data from Excel using react-data-export

I've been attempting to create an excel export feature, but for some unknown reason, it's not functioning properly. I'm utilizing react-data-export and followed a small test example from this GitHub link, yet the export is not working as exp ...

Ways to effectively pass arguments to the callback function within the catch function in JavaScript

While working on my code, I suddenly felt the need to pass an extra argument, "msg", to the callback function renderError(). This extra argument should be passed along with the default error argument generated by the catch function itself. I tried doing i ...

Utilizing lazy evaluation, multiple functions are triggered by ng-click in succession

Successfully disabled ngClick on an element when the scope variable (notInProgress) is set to true as shown below: <a data-ng-click="notInProgress || $ctrl.setTab('renewal');</a> Now, I want to include additional functions to be execut ...

Using the Mongoose $or operator with a nested array in query conditions

Here are the schemas I am using: //ProjectModel const ProjectSchema: Schema = new Schema( owner: { type: Schema.Types.ObjectId, ref: "User" }, users: [{type: Schema.Types.ObjectId, ref: "ProjectUser", unique: true }] ); //Project Use ...

Regex pattern is malfunctioning

I am having trouble understanding why this regex keeps returning false. I have an onkeydown event that should trigger it when pressing the 'w' key, but it doesn't seem to be working. var keyGLOB = ''; function editProductSearch ( ...

How can we stop the jumping of images in the grid? Is there a way to eliminate the jump effect?

Here is a script I am working with: <script src="http://static.tumblr.com/mviqmwg/XyYn59y3a/jquery.photoset-grid.min.js"></script> <script> $(document).ready(function() { $('.photoset-grid').photose ...

What methods can I use to compare a React Component across multiple pages with Cypress?

One task I am trying to tackle is comparing a component on one page with the same component on another page using Cypress. For example, let's say I have a Pricing Component on the Home page, and I want to verify if the values on the Pricing Page are i ...

What methods can I use to design a splash screen using Vue.js?

I am interested in creating a splash screen that will be displayed for a minimum of X seconds or until the app finishes loading. My vision is to have the app logo prominently displayed in the center of the screen, fading in and out against a black, opaque ...

The persistent problem with constantly polling the $.ajax request

One issue I'm facing involves a continuous polling $.ajax request. The challenge lies in initiating it immediately first, and then running it at intervals set in the setTimeout call. Take a look at the example code here. myObj = {}; var output = ...

Obtaining Runtime Inputs from the Command Line

I have been using a unique Vue SPA boilerplate found at this link, which utilizes webpack as its foundation. During the development process or when deploying the application, I have successfully utilized process.env.NODE_ENV to differentiate between a dev ...

Save your AngularJS SVG file as a JPG

I am attempting to develop a custom directive that will allow me to convert an SVG file into a JPG or PNG format. I stumbled upon this website: http://bl.ocks.org/mbostock/6466603 So, I decided to try and implement something similar with the following co ...

NextAuth encountered a CLIENT_FETCH_ERROR error while processing the session callback

Encountering issues while trying to set up nextauth v4. Keep getting this error: Client fetch error, Unexpected end of JSON input {error: {…}, path: 'session', message: 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON d ...