Implement a dropdown menu in Vue.js using data fetched from an ajax request

I am looking to utilize ajax calls in conjunction with to dynamically populate the options for a drop-down menu. Here's an example of what I currently have:

<select v-model="selected">
  <option v-for="option in options" v-bind:value="option.value">
    {{ option.text }}
  </option>
</select>
<span>Selected: {{ selected }}</span>

.js file

new Vue({
  el: '...',
  data: {
    selected: 'A',
    options: [
      { text: 'One', value: 'A' },
      { text: 'Two', value: 'B' },
      { text: 'Three', value: 'C' }
    ]
  }
})

However, instead of hard-coding the options, I want them to be generated from an ajax call.

An example of the ajax call is as follows:

function pullEmployees(){
        var eventOwnerId = $('#eventOwner').val();
        var eventOwnerName = $('#eventOwner :selected').text();
        $.ajax({
            url: "employees.cfm",
            data: {
                eventOwnerId: eventOwnerId,
                eventOwnerName: eventOwnerName,
                method : "updateOwners"
            },

            success: function(results) {
              // results will contain a list of objects with two properties (ID and Value)
            }
    });
}

I am new to using and would greatly appreciate any assistance.

Answer №1

Below is a demonstration where I am emulating your ajax call using a setTimeout. The main idea is to store the result of new Vue() in a variable and then assign the returned data from your ajax call to the options property of that Vue instance.

I have also made adjustments to your template to indicate that the options being returned follow the format {ID, text}.

console.clear()

let app = new Vue({
  el: '#app',
  data: {
    selected: 'A',
    options: []
  }
})    


function pullEmployees(){
  let options = [
    { text: 'One', ID: 'A' },
    { text: 'Two', ID: 'B' },
    { text: 'Three', ID: 'C' }
  ];
  setTimeout(() => app.options = options, 1000)
}
pullEmployees()
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e080b1b3e4c504c5048">[email protected]</a>/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="app">
  <select v-model="selected">
    <option v-for="option in options" v-bind:value="option.ID">
      {{ option.text }}
    </option>
  </select>
  <span>Selected: {{ selected }}</span>
</div>

However, all these steps can actually be performed within Vue itself without needing external functions.

let app = new Vue({
  el: '#app',
  data: {
    selected: 'A',
    options: []
  },
  methods:{
    pullEmployees(){
      var eventOwnerId = $('#eventOwner').val();
      var eventOwnerName = $('#eventOwner :selected').text();
      $.ajax({
        url: "employees.cfm",
        data: {
          eventOwnerId: eventOwnerId,
          eventOwnerName: eventOwnerName,
          method : "updateOwners"
        },
        success: results => this.options = results
      });
    }
  },
  mounted(){
    this.pullEmployees()
  }
})

If eventOwner is part of the Vue component, you could directly access that value as a data property from Vue.

Answer №2

Keep your vue instance stored in a variable:

var myVue = new Vue(// stuff...);

When dealing with Ajax, pay attention to the scope of this:

function fetchEmployees(){
        var _that = this; // connect "this" to local variable
        var eventOwnerId = $('#eventOwner').val();
        var eventOwnerName = $('#eventOwner :selected').text();
        $.ajax({
            url: "employees.cfm",
            data: {
                eventOwnerId: eventOwnerId,
                eventOwnerName: eventOwnerName,
                method : "updateOwners"
            },

            success: function(data) {
              _that.myVue.data.options = data; // update 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

The system has encountered an issue: "EntityMetadataNotFound: Unable to locate metadata for the entity named 'User

Just wanted to reach out as I've been encountering an issue with my ExpressJS app recently. A few days ago, everything was running smoothly without any errors. However, now I'm getting a frustrating EntityMetadataNotFound: No metadata for "User" ...

What is the best method for incorporating success icons into my website with vue.js?

Hey everyone, please excuse my lack of expertise as I am a beginner in this field. I'm trying to incorporate success icons into my website using bootstrap or similar tools, but I'm unsure of how to implement the if statement below. If anyone co ...

Adjustable Title in Line Plot

After receiving a JSON object from a web server in response, I am encountering some challenges with extracting and displaying the data. The JSON array consists of monthly key-value pairs like {"JAN":"17"}, {"FEB":"19"}, {"MAR":"21"}, etc. To display these ...

A visually stunning image showcase with dynamic resizing and strategically placed white spaces using the m

I'm attempting to create a responsive image gallery using the Masonry jQuery plugin, but despite reading numerous articles and forum posts on the topic, I can't seem to get it to work properly. The gallery is displaying many blank spaces. My app ...

I am interested in extracting information from a public Facebook post

Is it possible to scrape or utilize the FB API to retrieve data from a public profile's wall post? By inspecting the element on the URL, you can see most of the data as well as the ajax calls for infinite scrolling on the wall. How could one go about ...

An ultimate guide to mapping a nested array in React.js

Problem: I am struggling to display the entire content of my array. The goal is to render all elements in the array, but so far I can only get one to show up. I have found that including [key] in the object fields is the only way to generate any output. ...

Trouble getting AngularJS $scope arrays to populate with multiple PHP to MySQL queries

In my Angular controller, I used to fetch data from a PHP file that pulled one query from the database, stored it in a scope array, and displayed it on the webpage successfully. However, now I am trying to execute two queries in the same file. Each query ...

Switching on the click functionality

I was able to successfully toggle a boolean variable along with some other options. However, I encountered an issue when trying to create another click function for a different button to set the boolean variable to false. Here is my code: let manageme ...

Utilize Javascript to access Django Rest Framework API and obtain a Token

I've successfully set up an API with Django Rest Framework that functions well when accessed through cURL, HTTPie, or the browsable API. The API utilizes token authentication, requiring initial credentials to obtain a token. To achieve this using HTTP ...

Best practices for storing non-reactive and static data in a Vue application

Welcome to the community! I'm excited to ask my first question here on StackOverflow. I am currently working with vue.js-v2 and webpack. My goal is to ensure that data remains immutable for child components, which are loaded through the vue-router. T ...

Error encountered while attempting to invoke endpoint function

Recently, I was handed a Node.js API documented with swagger for debugging purposes. My task also involves implementing some new features, however, I've encountered some difficulty when it comes to calling the functions that are executed upon hitting ...

Vue Component not Updating even though the URL is changing

Encountering a problem where the URL updates but the page does not refresh. On the homepage, I have a list of projects. When clicking on a project, it should lead to "website.com/project/project-1" and function correctly. However, at the bottom of that p ...

What is the process for accessing a URL using a web browser and receiving a plain text file instead of HTML code?

Hello there! I've created a simple HTML file located at that can display your public IP address. If you take a look at the code of the page, you'll notice that it's just plain HTML - nothing fancy! However, I'm aiming for something mo ...

Incorporating PHP in JS/jQuery AJAX for creating unique odd and even conditional layouts

My PHP code includes a loop that changes the layout of elements based on whether the $count variable is odd or even. For odd counts, an image appears on the left and text on the right. For even counts, it's the other way around. To load content dynam ...

Encountering a Component Exception error in React Native while attempting to implement a Victory chart component

Currently, I am exploring the Victory library for react native to create a line chart for my budgeting application. Below is the code snippet from my Graph component: import React from 'react'; import { View, StyleSheet } from 'react-native& ...

Grunt is throwing an error message of "Cannot GET/", and unfortunately ModRewrite is not functioning properly

I've recently started using Grunt (just began last Friday). Whenever I run Grunt Serve, it displays a page with the message "cannot GET/" on it. I tried implementing the ModRewrite fix but the error persists. Any assistance would be highly appreciat ...

Testing Vue components by simulating behavior on methods in the TDD process

As I delve into the world of TDD while constructing my Vue app, I am dedicated to only writing the necessary production code to pass failing unit tests. I find this methodology quite satisfying, but have hit a stumbling block when it comes to adding method ...

Discovering the process to retrieve an uploaded image with vue.js

Help needed with a code snippet for multi-upload images in Vue.js. The functionality issue I am facing is that when uploading an image, only the image name appears in the console terminal instead of the actual image. I want to save the image in the backend ...

One way to transfer data from a Vue table component to another Vue table component is by including an edit button on each row in the table. This allows

When working with two table components, one fetching records using axios and the other needing to get records after clicking on the edit button in the parent component, I encountered issues. Despite attempting Vue's parent-to-child component communica ...

What happens when tabs are dynamically added on keypress?

I am encountering issues with this code snippet. $('body').on("keypress", ".message", function(e) { if ( e.keyCode == 13 && $(".message").val().length > 0 ) { input = $(".message"); // Check for join com ...