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

Troubleshooting issue with jquery.i18n.properties functionality

I am encountering an issue with implementing jQuery internationalization. I have included the files jquery.i18n.properties.js, jquery.i18n.properties-min.js, and jquery-min.js in my resources folder. In my jsp, I have added the following code: <script ...

I am encountering an issue where my Vue navbar is successfully changing the route but not updating the corresponding router-view

I have been working on a single-page application using Vue and I encountered an issue with the navbar when navigating through routes. The problem is that after the first click on a navbar item, the route changes successfully but the router-view does not up ...

Issues with routing on Zeit Now platform are causing a 404 NOT FOUND error when attempting to reload pages that are not the

Recently, I purchased a Next.js template from Themeforest and attempted to deploy it to Zeit Now. This particular project is set up as a monorepo using Lerna and Yarn workspace. The code for the Next.js app can be found inside the packages/landing folder. ...

Navigating Divs Using jQuery

I am working with a class that has multiple divs, each with a unique id attached to it. I am using jQuery to dynamically cycle through these divs. This is a snippet of my HTML code: <div id ="result">RESULT GOES HERE</div> ...

Error: Unable to assign the 'schedule' property to a null value

I'm currently developing a scheduling application using React.js and have implemented a draggable scheduling feature for users to indicate their availability. Everything seems to be working smoothly, except for one pesky error message: TypeError: Cann ...

Managing multiple Angular calls when additional submit buttons are present

I am working on a form that includes a drop-down menu, check box, and four buttons. Whenever any action is taken (such as checking/unchecking the box, selecting an option from the drop-down, or clicking a button), it should trigger a service call to update ...

Having trouble retrieving data sent via ajax in PHP

Currently, I am using Ajax to send a variable in my PHP file. Here's the code snippet: getVoteCount: function(){ App.contracts.Election.deployed().then(function(instance) { for(i=0; i<4; i++){ instance.candidates(i).then(functi ...

What methods can I use to ensure that a user's credentials are not shown in the URL?

My NextJS application sometimes behaves unexpectedly. Whenever I have a slow connection and the initial load time of the site is longer than usual, after trying to log in to the application, the credentials I entered are displayed in the URL. This happens ...

Stack two divs together

It may seem silly, but I just can't get it to work. I'm attempting to enclose two divs with different classes in another div, but my current code is automatically closing the divs. There are multiple sets of divs with classes .panel-heading and ...

What is the best way to retrieve and display a PDF file through an API in VueJS?

I am looking to display a file from my API in my VueJS client. Specifically, when accessing a certain URL, the file (pdf, text, or image) should open if the browser supports it (similar to how Chrome opens PDFs). I want to achieve this using VueJS or just ...

Encountering an issue while trying to utilize Vuex in Vue with TypeScript

I recently utilized npm to install both vue (2.4.2) and vuex (2.3.1). However, when attempting to compile the following code snippet, I encountered the following error: https://i.stack.imgur.com/0ZKgE.png Store.ts import Vue from 'vue'; import ...

What is the process for converting a string into a date while disregarding the time zone

Due to the way dates are stored, it is important for me to retrieve them exactly as they are stored, but time zones are causing issues. moment("2020-10-28T08:41:00.000Z").format("YYYY-MM-DD HH:mm") // Result: 2020-10-28 09:41 However, ...

Response coming from an ajax call in the form of a JSON

With the JSON string provided below: {cols:[{"id":"t","label":"Title","type":"string"},{"id":"l","label":"Avg ","type":"string"},{"id":"lb","label":"High","type":"string"},{"id":"lo","label":"Low","type":"string"}],rows:[{"c":[{"v":"Change navigation"},{"v ...

Unable to upload file on ReactJS platform

I'm facing an issue while trying to upload a file and text using a form. The file doesn't get uploaded, although it works fine with Postman. Can anyone identify the problem? Thank you Axios function : postArticles : (content, attachment, header ...

All the details from this run are available in the npm run dev log on Ubuntu

Good day! I've been working on deploying a page built in vue.js, and after uploading all the files successfully, I encountered an issue when trying to run "npm run dev." No matter what I try, including re-installing npm dependencies and starting from ...

Adding optional properties to TypeScript interfaces

As discussed in this post, the optional ? operator is commonly used to indicate that a function parameter can be omitted. But what is the significance of the ? operator when it appears on interface parameters? For instance, consider the following TypeScrip ...

JQuery for Seamless Zoom Functionality

I am working with some divs that have images as backgrounds, and I have added a zooming effect on hover. However, the zoom effect is not smooth. Is there a way to modify the script to make the zoom effect smoother? Here is an example of my HTML structure: ...

Showing recurring HTML elements with conditional content

I am displaying multiple bootstrap badges in a table column with different colors based on the values. Each badge has a unique class and style name to differentiate the colors. I feel like there is a lot of repetition in my HTML code. Is there a way for me ...

Mastering card sliding and spacing in React NativeLearn how to effortlessly slide cards horizontally in your React

My aim with the following code snippet is to achieve two objectives: Apply a margin of 20 units to each card Display all four cards in a single row, allowing users to swipe horizontally Unfortunately, I have not been successful in achieving either of th ...

Can the details of a package be retrieved from a Nuget private store using a REST API?

Currently working on an Angular 8 project that involves displaying the details of Nuget packages from a custom store. I am wondering if it is possible to retrieve package details from an NPM custom store using a REST API? Something similar to: https://lea ...