How to render an array in VueJS using the v-for directive

Upon receiving the GET request, the JSON response is as follows:

[{"key":"COMPLAINT","value":"Complaint"},{"key":"DONATE_ENQ","value":"Donation Enquiry"},{"key":"GENERAL_ENQ","value":"General Enquiry"},{"key":"MEMBERSHIP_ENQ","value":"Membership Enquiry"},{"key":"VOL_ENQ","value":"Volunteer Enquiry"}]

Here is the JS code snippet:

getEnquiry: function getEnquiry() {
                this.applicant1.option_lookup = document.getElementById('hdnOptionsLookup').value;
                var optionLookupName = this.applicant1.option_lookup;
                axios.get("/TESTAPI/Lookup/Enquiry?optionLookupName=" + optionLookupName).then(function (response) {
                    this.applicant1.enquiry = response.data;
                    var test = this.applicant1.enquiry;
                    alert(test);
                    console.log(response.data);
                    this.loading = false;
                }, function (error) {
                    console.log(error);
                    this.loading = false;
                });
            },

The JS variable is defined as shown below:

 applicant1: { enquiry: [{ key: "", value: "" },
                        { key: "", value: "" },
                        { key: "", value: "" },
                        { key: "", value: "" },
                        { key: "", value: "" }], 
                 }

The objective is to display each key and value pair in the HTML like so:

<div class="form-group" v-bind:class="{input_error:applicant1.enquiry_error}">
                                <select id="applicant1_enquiry" class="form-control" v-model="applicant1.enquiry">
                                    <option :value="null">Select the reason for your enquiry</option>
                                    <option v-for="enq in applicant1.enquiry" :value="enq.key">{{enq.value}}</option>
                                </select>
                            </div>

However, the values are not appearing in the drop-down list. Any assistance would be greatly appreciated. Thank you.

Answer №1

To improve the efficiency of your API requests and data handling, consider implementing Vuex in your project:

Visit Vuex documentation

By utilizing Vuex, you can retrieve API responses across various components, expanding the scope beyond the initial caller.

Answer №2

Dealing with reactivity issues is a common challenge. Here are a couple of solutions you can try:

var self = this
axios.get("/TESTAPI/Lookup/Enquiry?optionLookupName=" + optionLookupName).then(function (response) {
  self.applicant1.enquiry = response.data
  self.applicant1 = JSON.parse(JSON.stringify(self.applicant1))
  self.loading = false;
}, function (error) {
  console.log(error);
  self.loading = false;
});

Alternatively, you can use

Vue.set(self.applicant1, 'enquiry', response.data)

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

JavaScript variable not refreshing its value after submitting an HTML form

In my HTML form, I have 8 textboxes enclosed in div tags with IDs ranging from fa1 to fa8. By default, two of the textboxes are visible while the remaining six are hidden. To toggle the visibility of these divs, I've implemented two buttons - addfa an ...

Removing custom scrollbars using jQuery from an element

Utilizing mCustomScrollbar with jQuery UI dialog boxes. When attempting to initialize mCsutomScrollbar on $(window).load as instructed, it fails because the dialogs are not yet visible. As a workaround, I've had to initiate mCsutomScrollbar on the op ...

Displaying an HTML string on a webpage

I am developing a user dashboard using Django for a Python-based web application. This web application generates emails, and the HTML content of these emails is stored in a file (and potentially in a database table as well). As part of the dashboard's ...

A guide on viewing the output of an AJAX request using Python and Selenium

Currently experimenting with Selenium testing on a Django website. I recently implemented a feature to track javascript errors through Google Analytics. How can I create a test to verify that when a javascript error occurs, an AJAX request is triggered a ...

Converting a one-dimensional array into a two-dimensional array in JavaScript explained

Below is the code snippet const arrayColumn = (arr, n) => arr.map(x => x[n]); const pcorr = (x, y) => { let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0, sumY2 = 0; const minLength = x.length = y.length = Math.min(x.length, y.le ...

How can I use jQuery to automatically redirect to a different HTML page after updating a dynamic label?

When I click on a button in first.html, a function is called to update labels in second.html. However, despite being able to see second.html, I am unable to see the updated values in the labels. Can someone please advise me on how to achieve this? functi ...

Husky and lint-staged failing to run on Windows due to 'command not found' error

I'm facing issues with getting husky and lint-staged to function properly on my Windows 10 system. Here's how my setup looks like: .huskyrc.json { "hooks": { "pre-commit": "lint-staged" } } .lintstagedrc ( ...

Switching visual content according to dropdown choice

Hey there! I've been working on my HTML file and ran into a little issue. I'm trying to change the image in the div section based on a dropdown selection that modifies the source of the image from an XML file. However, I keep getting an error tha ...

Angular Chart.js is throwing an error: "Uncaught SyntaxError: Cannot use import statement outside a module"

Upon opening the page, an error in the console related to Chart.js 4.2.1 is being displayed. Description of first image. Description of second image. Is it possible that this issue solely lies with Chart.js? How can it be resolved? To address the proble ...

Utilizing the map function to modify the attributes of objects within an array

I have a data structure with unique IDs and corresponding status keys. My goal is to count how many times each status repeats itself. Here's an example of my data structure: const items = { id: 2, status_a: 1, status_b: 1, status_c: 3 }; Below is the ...

Angular 7 error: No provider found for PagerService causing NullInjectorError

I have been struggling to get pagination working properly in my project. Below is the code I have written: pager.service.ts: import * as _ from 'underscore'; @Injectable({ providedIn: 'root', }) export class PagerService { ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

Tips for verifying the "truthiness" of an object, removing any falsy values, and making changes to the object

I am faced with the task of examining each property of an object to determine if it is truthy, and then removing any that are not. var user = { name: 'my name', email: null, pwHash: 'U+Ldlngx2BYQk', birthday: undefined, username: &ap ...

When a mobile device is rotated, the screen on a jQuery application will automatically shrink

Having trouble with JQM and device rotation on iOS devices. The screen doesn't resize properly when rotated. I have this line in the header to handle display size: <meta name="viewport" content="height=device-height,width=device-width,initial-scal ...

Setting up a custom UI Kit and font package with Laravel 5.6 and Vue.js

I am currently facing some challenges while trying to integrate Now-UI-Kit into my Laravel 5.6 project with vue.js. For reference, the URL to access the Now-UI-Kit is: Prior to this, I was able to successfully install a plain UI Kit by following straight ...

Observable not defined in facade pattern with RxJS

(After taking Gunnar's advice, I'm updating my question) @Gunnar.B Tool for integrating with API @Injectable({ providedIn: 'root' }) export class ConsolidatedAPI { constructor(private http: HttpClient) { } getInvestments(search?: ...

Troubleshooting a React JS and material-ui issue

Having an issue with material-ui integration in reactjs. Attempting to render a FlatButton, but encountering the error message: TypeError: _context$muiTheme is undefined As a newcomer to reactjs, I'm unsure of where the problem lies. Below is my code ...

Retrieve the current element's 'this' object even after binding an external 'this' object

Is the title of this question confusing? Let's dive in. Imagine you have something like this: var Test = function(){ this.foo = a; } Test.prototype.init = function() { $(document).on('change', '.form-control', this.myFun ...

Errors arising in Codesandbox with Vue-cli and Vuetify integration

While my project runs smoothly on my computer, I am encountering warnings in codesandbox. What could be causing this discrepancy? Check out the codesandbox link: https://codesandbox.io/s/github/Tauromachian/vue-select-list You can also find the project ...

Guide to emphasizing text with hover effects and excluding whitespace (javascript)

Currently, I am utilizing jQuery for hover highlighting purposes. However, I am facing an issue where the entire div gets highlighted instead of just the text. I attempted to use an "a tag" but don't want a reference link. I know this should be a simp ...