Loading initial data in Vue.js

I am facing an issue with loading data from REST services to populate comboboxes in a form. The problem is that the working model gets loaded before the required data for the comboboxes, resulting in them not being set to the correct value.

The only way I can make it work is by setting the load model inside the load dropdown callback. However, this approach seems messy and does not work when there are more than one dropdown on the form.

Can anyone suggest a solution for this problem using Vue?

Below is the script:

var app = new Vue({
    el: '#categoryEdit',
    data: {
        category: {},
        categories: []
    },
    methods: {
        getCategory: function(categoryId) {
            const config = {
                headers: {
                    'Authorization': 'Bearer ' + '@token'
                }
            };
            axios.get('/api/categories/' + categoryId, config)
                .then(function(response) {
                    app.category = response.data;
                    console.log(app.category);

                })
                .catch(function(error) {
                    alert(error);
                    console.log(error);
                });
        },
        add: function() {
            const config = {
                headers: {
                    'Authorization': 'Bearer ' + '@token'
                }
            };
            axios.post('/api/categories/save', app.author, config);
        },
        fetchCategories: function() {
            var config = {
                headers: {
                    'Authorization': 'Bearer ' + '@token'
                }
            }

            axios.get('/api/categories/all', config)
                .then(function(response) {

                    app.categories = response.data;

                })
                .catch(function(error) {
                    alert(error)
                    console.log(error);
                });
        }
    },
    mounted: function() {
        this.fetchCategories();
        this.getCategory('@ViewContext.RouteData.Values["id"]');
    }
})

And here's the HTML:

<div class="form-group">
    <label class="col-md-3 control-label">Kategorija</label>
    <div class="col-md-9">
        <select class="form-control select2 select2-hidden-accessible" v-model="category.ParentCategoryId">
            <option v-for="cat in categories" :value="cat.Id">
                {{cat.Name}}
            </option>
        </select>
    </div>
</div>

Answer №1

To optimize category loading, ensure all categories are loaded before attempting to load a specific category:

mounted: function() {
  this.fetchCategories()
    .then(() => {
      this.getCategory('@ViewContext.RouteData.Values["id"]')
    })
}

To achieve this, confirm that the fetchCategories method returns a promise:

fetchCategories: function() {
  var config = {
    headers: {
      'Authorization': 'Bearer ' + '@token'
    }
  }

  return axios.get('/api/categories/all', config)
    .then(response => {
      this.categories = response.data;
    })
    .catch(error => {
      alert(error)
      console.log(error);
    });
}

Furthermore, it is recommended to bind all data to the this object for better encapsulation within your Vue instance.

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

Display a div in a specific color depending on whether the value is positive or negative, and

I created a counter but I want to change the color of the id="clicks" based on whether the value is positive or negative, and also add text accordingly. var clicks = 0; function clickplus() { clicks += 1; document.getE ...

Tips for iterating over two models using ng-repeat

I'm a newcomer to Angular and I have an issue that requires a neat solution: I have a div element called "SelectedList" that needs to display a list of active elements from another container. This container contains two tabs, Tab1 and Tab2, which are ...

Is there a way for me to collaborate on a footer control with a different website?

Is it possible to seamlessly incorporate a footer from one website into another? Ideally, I want the footer HTML (and styles) to be dynamically inserted into different web pages. The common workaround is using an iframe, but this causes navigation issues ...

Vuetify has encountered an error due to exceeding the maximum call stack size

I am currently utilizing Vuetify Dialog in my code snippet below <v-dialog max-width="390" persistent v-model="dialog"> <template v-slot:activator="{ on }"> <v-btn icon v-if="el.items_count == 0" v-on="on" > <v-icon> ...

Can we iterate through custom variables in JavaScript?

Can the "iterate" function be implemented without using deprecated JavaScript features to loop through its own variables? (function () { var a = 1; var b = 2; var iterate = function () { // code to iterate over variables here }; }) ...

Removing a row from a table with the click of a button

I recently wrote a piece of code to dynamically add or delete rows in an HTML table. The issue I'm facing is that while the addition of rows works perfectly fine, I'm unable to delete a specific row. Upon clicking the delete button, I encounter a ...

How can I upload an image file using VueJS and Django Rest Framework?

Hello, I am currently in the process of editing a blog page using VueJS and Django Rest Framework. However, I am facing an issue when trying to upload a photo - I keep receiving an error message stating that "the sent data is not a file." Additionally, I a ...

What are some ways to implement pagination on a website?

Struggling to implement pagination without Laravel? You're not alone. The challenge lies in creating a cycle that displays the correct number of pages, with each page containing 10 posts out of a total of 98. While you've managed to calculate the ...

I'm having trouble grasping the significance of the "i" in the forEach function within my code

Trying to determine word frequencies, but struggling with the code. Here's what I have: function check(){ var word = document.querySelector('textarea').value.split(" "); frequency ={}; word.forEach(function(i){ console.log(i) ...

How can I apply JavaScript to aggregate child node values and assign them to the parent in JSON data format?

I receive a dynamic JSON from the server, which has varying structures. Each data entry consists of a chapter with stages and/or review sets at the root level. If a stage exists, there will be either a review set array or another stage. The review set cont ...

How to access a webpage on your Android device without the address bar visible

My question relates to sending Push Notifications through OneSignal. Upon clicking a push notification, it automatically redirects the user to my website. Is there a way to hide the address bar on the browser when this happens? I attempted using the follo ...

First Impressions of Datatables

Is there a way to display a specific range of rows with Datatables initially? For example, showing rows 100-105 only. Does anyone know if this is achievable using the options available? ...

Leverage JSON data from an API within JavaScript, sourced and accessed through PHP

I'm seeking advice on using JSON data (loaded in PHP) with JavaScript. I am currently retrieving the JSON from an API, but someone suggested that using curl would be more efficient? I've attempted to research curl, but haven't found exactly ...

jQuery Color Plugin - The issue is that $.Color is not registering as a function

I have been attempting to get the demo from jquery-color up and running, but I keep encountering the error message $.Color is not a function. Can anyone point out what mistake I might be making? Here is the relevant snippet of code: $("#sat").click(funct ...

What steps should I take to incorporate this feature into my Meteor project?

After successfully installing the type.js package, I discovered that the code works fine when directly executed in the console. Here is the code snippet: $(function(){ $(".typedelement").typed({ strings: ["You don&apo ...

What is causing the PUT request to not go through when using POSTMAN?

As I navigate through the paths of my application, I encountered an issue with PUT requests that were not being fully processed by POSTMAN. Below is the configuration of my ExpressJS server: const express = require('express'); const morgan = re ...

Is Search Highlighting Keywords Causing Issues with URL Variables?

In my current javascript function, I am using the following code to highlight keywords: for (var i = 0; i < keywords.length; i++) { var a = new RegExp(keywords[i], "igm"); container.innerHTML = container.innerHTM ...

What could be the reason behind receiving a 406 Not Acceptable status at the client side from the server, and why is my Spring controller not being triggered?

Here is the code for an AJAX GET request: $("#tabsss2").click(function tab1() { $.ajax({ type: "get", traditional: true, dataType: 'json', url: "DataGridServlet.htm", cache: false, ...

Custom input field in Material UI not communicating properly with Redux form

I am currently utilizing Material UI and React to implement a custom input field. While using redux form for form validation, I have encountered an issue where the onBlur and onFocus events are not being dispatched successfully. Interestingly, if I switch ...

Using Angular 4 with Bootstrap dropdowns necessitates the use of Popper.js

I recently created an Angular 4 CLI app. After executing the following command: npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="066469697275727467764632283628362b64637267">[email protected]</a> jquery ...