Vuejs Issue with reactivity when passing data from ajax request to select element

Trying to create a dynamic select input that updates its options based on an AJAX response. When using hardcoded data, everything works fine. However, when attempting to populate the options dynamically using the AJAX response, reactivity is lost.

For example, with the object {Foo: 'Bar', Lorem: 'Ipsum'}:

<select>
  <option value="Foo">Bar</option>
  <option value="Lorem">Ipsum</option>
</select>

The issue arises when trying to make the data dynamic using this function:

$.get('/registrar/levels', function (data) {
   for (const datum of data) {
     addModal.levelFields[datum.name] = datum.id;
   }
});

The desired dropdown functionality looks like this:

Vue.component("modal-add-form", {
props: {
    formName: String,
    formType: [String, Number],
    options: Object,
},
template: `<div class="form-group" v-if="formType !== 'select'">
                <label :for="formName" v-text="formName"></label>
                <input :type="formType" class="form-control" :name="formName" :id="formName" value="" :placeholder="formName">
            </div>

            <div v-else>
                <select :name="formName" class="form-control">
                    <option v-for="(value, name) in options" :value="value" v-text="name"></option>
                </select>
            </div>`

});

Answer №1

It's not recommended to directly reassign data values in Vue as it may not trigger the appropriate reactivity system. It's best to use Vue.set or this.$set to ensure proper detection and view rerendering:

$.get('/api/levels', (data) => {
   for (const item of data) {
     this.$set(this.formFields.levels, item.name, item.id)
     // formFields.levels[item.name] = item.id;
   }
});

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

What could be causing worker threads to fail when instantiating a class from a separate file?

The following TypeScript file is being used: import { Worker, WorkerOptions, isMainThread, parentPort } from "worker_threads"; import path from "path"; export class SimpleWorker { private worker: any; constructor() { i ...

Tips for segmenting text into pages according to the dimensions of the viewport and the font style

Here's a puzzle for you. I have a horizontal slider that loads pages via Ajax, with pre-loading features to maintain smooth performance. Similar to Facebook Billboarding but with a slight twist. By determining the viewport size, I calculate boxSizeX a ...

JavaScript, can you explain the significance of the "length" set in this function?

I found this code snippet online and used it in my function. Surprisingly, it works perfectly. However, I'm puzzled by the use of .length in the for loop statement. Isn't length a measurement of how long something is? It's somewhat like ...

Surprising SMTP reaction encountered during an ajax call

I've encountered an unusual response in my AJAX SMTP setup. The PHP code I'm using for SMTP is as follows: require_once 'PHPMailer/PHPMailerAutoload.php'; $response = array(); //Creating a new instance of PHPMai ...

React/Redux encountered a roadblock when attempting to iterate through an array stored in the state

Currently, I am delving into the world of React/Redux and have encountered a stumbling block while transitioning one of my single-page web applications to this framework. What I aim to achieve is to populate an array in the initial state of the web app wit ...

Disable the border and background colors in CloudFlare Turnstile

I have implemented the CloudFlare reCaptcha Turnstile and I am looking to modify the widget by removing the border and background color. I believe this customization can be achieved using CSS or Javascript. Thank you for any assistance! ...

Tips on transforming a JSON array object into a JSON array

**Background:** I have been utilizing lodash to eliminate the empty key from my JSON data. However, upon removal of the keys, it transforms my array into an object. For instance: { "projection": "Miller", "series": [ { "mapPolygons": { ...

Screen alerts in compliance with regulations

Each time a model is created, deleted, or modified, all connected sockets are notified through the Sails autowatch setting. While this is useful to some degree, I am looking to customize these notifications at a certain point. In my application, I have sp ...

AJAX Response: No data available

I am currently attempting to retrieve data from a SQL server and showcase it on a webpage using [WebMethod] by following this tutorial. However, I have customized the data and logic for my own use. Objective - To display the count of incidents based on Pr ...

What causes the button size to change in Bootstrap when switching to a spinner?

Every time I switch from a spinner back to a button, the button's size changes. I am struggling to identify the cause of this issue. function resizeButton() { var btn = document.getElementById('submitBtn'); btn.innerHTML = ' ...

What could be the reason my ImageMapster jquery plugin is not functioning in the Power Apps portal's code editor?

I'm attempting to add hover effects to an image map within my Power Apps portal site using the code editor. However, when I include the script: <script type="text/javascript">$('img').mapster();</script> for the desire ...

Enabling postcss compatibility with jss in Material UI

I came across an issue while using material UI: I need to add prefixes to CSS for my app to work in older browsers, for example: display:flex; What I'm looking for is a way to automatically add compatibility after packaging, like this: display: -we ...

A guide on setting up a countdown timer in Angular 4 for a daily recurring event with the help of Rxjs Observable and the Async Pipe

I'm currently working on developing a countdown timer for a daily recurring event using Angular 4, RxJS Observables, and the Async Pipe feature. Let's take a look at my component implementation: interface Time { hours: number; minutes: numbe ...

Customizing AxiosRequestConfig with Axios in TypeScript can greatly enhance the functionality and

Currently working with React and Axios. Lately, I've been experimenting with custom configurations in Axios as shown below: import $axios from 'helpers/axiosInstance' $axios.get('/customers', { handlerEnabled: false }) However, wh ...

The error message states that the object function defined as `(req, res, next) { app.handle(req, res, next); }` does not contain the method 'configure'

Could somebody help me understand why I encounter this error when attempting to execute the code below? var express = require('express'); var login = require('./routes/login'); var app = express(); //all configurations app.confi ...

What is the most efficient way to enable seamless communication between sibling components in Vue.js 2?

Just starting out with Vue.js 2 and I'm really enjoying it so far despite being new to it. Currently using the latest version. I've begun working on my first larger application and ran into a scenario right off the bat where I have a main app co ...

Is there a way to seamlessly update the content across all devices being used in a Rails app?

I'm completely stumped on how to tackle this issue. I want the app users to instantly see any new posts added or removed by the admin without having to manually refresh the page. After some research, I came across websockets as a potential solution. H ...

How can I display the Bootstrap 5.3.0 Collapsible button on this basic website?

I've been struggling to implement a Bootstrap Collapsible on my web page using Bootstrap version 5.3.0. I've tried different approaches but I can't seem to get it to work. All I need is a Collapsible that contains a few links, which should b ...

Send a Javascript variable to a Python controller using AJAX

Programming is still new to me and I find myself in unfamiliar territory... I am working on creating an app that relies on button clicks to gather information and provide data analysis based on those interactions. While this functionality works using pure ...

Redirecting with response headers in Next.js

Objective: The Goal: Clicking a button on a page should send a request to the controller. The controller will then set a cookie, and upon receiving the response, redirect the page to another page, such as the about page. Directly Calling API route from th ...