Transforming a Vue.js sample to incorporate ajax requests

For my latest project, I am incorporating Vue.js. One part of the project requires rendering a tree view that is stored in a database. I have taken inspiration from the Vue.js tree view example and have successfully retrieved the data from my server in the correct format.

I have managed to tweak the example to load the data from JavaScript. However, there is a delay as the component is already rendered by the time the data loads. I have confirmed that the data functions properly when I preload a variable with the server data.

How can I adjust the setup to allow for loading data via AJAX?

This is my JavaScript:

Vue.component('item', {
    template: '#item-template',
props: {
    model: Object
},
data: function() {
    return {
        open: false
    }
},
computed: {
    isFolder: function() {
        return this.model.children && this.model.children.length
    }
},
methods: {
    toggle: function() {
        if (this.isFolder) {
            this.open = !this.open
        }
    },
    changeType: function() {
        if (!this.isFolder) {
            Vue.set(this.model, 'children', [])
            this.addChild()
            this.open = true
        }
    }
}
})

var demo = new Vue({
    el: '#demo',
data: {
    treeData: {}
},
ready: function() {
    this.fetchData();
},
methods: {
    fetchData: function() {
        $.ajax({
            url: 'http://example.com/api/categories/channel/treejson',
            type: 'get',
            dataType: 'json',
            async: false,
            success: function(data) {

                var self = this;
                self.treeData = data;

            }
        });
    }
}
})

The template:

<script type="text/x-template" id="item-template">
  <li>
    <div
      :class="{bold: isFolder}"
      @click="toggle"
      @dblclick="changeType">
      @{{model.name}}
      <span v-if="isFolder">[@{{open ? '-' : '+'}}]</span>
    </div>
    <ul v-show="open" v-if="isFolder">
      <item
        class="item"
        v-for="model in model.children"
        :model="model">
      </item>
    </ul>
  </li>
</script>

And the HTML:

<ul id="demo">
  <item
    class="item"
    :model="treeData">
  </item>
</ul>

Answer №1

There seems to be an issue with the $.ajax() call. The value of self within the success handler is incorrect.

success: function(data) {
    var self = this;    // this = jqXHR object
    self.treeData = data;
}

To resolve this, you can either utilize the context option and reference this.treeData

$.ajax({
    url: 'http://example.com/api/categories/channel/treejson',
    type: 'get',
    context: this,    // informs jQuery to use the current context as the context for the success handler
    dataType: 'json',
    async: false,
    success: function (data) {
        this.treeData = data;
    }
});

Alternatively, you can adjust the placement of the var self = this line right before $.ajax();

fetchData: function () {
    var self = this;

    $.ajax({
        url: 'http://example.com/api/categories/channel/treejson',
        type: 'get',
        dataType: 'json',
        async: false,
        success: function (data) {
            self.treeData = 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

Tips on how to select only the currently active tab and change its background color

I am currently troubleshooting the AJAX tabs functionality on my website. The issue I am facing is that the current code does not apply any styling to indicate an active tab. I believe I may need to use some JavaScript code to address this problem, but I ...

How to dynamically disable options in a Vuetify v-select based on the type of object value

When utilizing the Vuetify v-select component and setting the prop multiple, we can select multiple values at once. In this scenario, I have a variety of recipes categorized under Breakfast or Dinner using the parameter type. The goal is to deactivate al ...

Attempting to sort through elements in JavaScript

I'm looking to filter specific films based on choices made in the dropdown menus below. <select id="filmDropdown"> <option value="0">All Films</option> <option value="1">Film 1</option> <option ...

arrangement of columns within the <select> element

I have been attempting to create a column layout inside of <select> using CSS, but so far I have been unsuccessful. https://i.sstatic.net/ltIDl.png This is the HTML code I have tried: <select id="select-bill-period"> <option>Select ...

Nuxt.js does not support Vuex Mutation functionality

Just diving into vuex and nuxt, so there might be a simple solution to this issue. I have two middlewares: one that makes an API call using AXIOS to GitHub and another that pulls from an RSS feed of a medium.com user and converts it to JSON. The mutation ...

Initiate the second ajax function depending on the data received from the initial function

Having trouble using a textbox value retrieved by an AJAX function as data for another AJAX function. The second AJAX function is not working, no errors are showing in the console, and no object is being created. Below is the code for the two functions (t ...

How can I set up a MySQL table so that one field's value is dependent on whether another field has a value?

Currently, I am in the process of developing a website using HTML, PHP, JavaScript, and MySQL. On my website, there is a form where I need to input a student's ID and the name of a course that the student has passed. However, some courses have depend ...

Make a tab the active tab within the Material-UI tab component

For the current project, I have decided to utilize Material UI as the primary library. One of the pages in the project requires four tabs, which I am implementing using the tab component from the Material UI library. By default, when rendering the page wi ...

Is it possible to remove Sprites from a three.js scene?

Currently facing an issue where I am trying to update axis labels on a 3D plot by removing the old labels (implemented as sprites) before adding new ones. Unfortunately, I am experiencing difficulties. The previous labels seem to persist in the scene even ...

The jquery function is functioning properly, but it only behaves as expected when clicked

Currently, I have implemented this JavaScript function: $(".plusmenus1").on('click', function() { $('.plusmenus1 i').toggleClass("fa-plus fa-minus"); $("#care_and_washing").toggleClass("collapsed_MB "); changeHeight(); }); ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...

How to Retrieve the Current div's ID in VueJS

When using the v-for directive to dynamically generate an id for my div, I need to pass this unique id to a specific function. <div v-for="(item, index) in items" :key="index" :id="'form' + index" > ...

How much time can the browser dedicate to running JavaScript before moving on to loading a new page?

The webpage contains multiple hyperlinks. I want to monitor user clicks on these links. Whenever a user clicks on a link, an Ajax request is sent to my server for processing. The server then returns relevant data, which is further processed on the client ...

Data Sharing Among Components in Vue without Using Parent/Child Relationship

I'm working on an HTML site and I want to incorporate some Vue.js components onto the page. For example, I'd like to have an input field in the header as a Vue component. <header><search-component></search-component></header ...

Execute the JQUERY keyup function only if the mouse is not currently hovering over the input field

I'm struggling with the keyup function issue. My ordering form contains a certain number of items, some of which are grouped as follows: Item 1 - Group1 Item 2 - Group1 The grouped items have two input fields each, one hidden and one visible. I am ...

Passing Node.js MySQL query results to the next function within an async.waterfall workflow

In my node.js code using express, I have set up a route to request data from a mysql database. My goal is to pass the returned JSON in tabular form to another function to restructure it into a hierarchy type JSON. I have individually tested the script to ...

Generate unique IDP SAML replies

Currently, I am working on creating unit test cases for validating SAML responses. To achieve this, I am seeking guidance on generating multiple SAML responses in XML format using the necessary certificates and private keys. Are there any Node.js librari ...

The most effective method for transferring asynchronous data to pages in Next.js

My current directory structure: - components - NavBar - Header - Layout - pages - pages - demo.js - _app.js - index.js // index.js import React from 'react'; import NewLayout from "../../components/NewLayout/NewLayou ...

Using Functional Programming with Node.js: A guide to waiting for a function to complete

As a newcomer to Node.js, I am satisfied with the syntax of JavaScript as I have utilized it for constructing web interfaces. With substantial experience in Object-Oriented Programming from Java and C#, along with an understanding of functional programming ...

Why does the AngularJS ngRepeat filter permanently remove null values?

Check out this JSFiddle demonstration I created to illustrate the problem: http://jsfiddle.net/s6Lj2/2/ Observe that in the dataset $scope.places = [{ name: 'Chicago', status: 'Active', analyst: 'Sam', recor ...