implementing data in a single component using vue.js

I am facing an issue with a component where I need to fetch data using an ajax call. The component is being called correctly and the data is returned in the ajax call, but I am struggling to assign it to the data in the template?

<template>

    <div class="class-hero" id="dashboard-hero" :style="{ 'background-image': 'url(' + last.content_image + ')' }">

        <div class="class-hero-overlay"></div>

        <div class="class-hero-container">

            <h1> {{ last.content_name }}</h1>
            <p> {{ last.content_description }} </p>


            <div class="class-stat">
                <div id="classesCirle" class="hero-class-progress"></div>
                <p>Modules</p>
            </div>
            <div class="class-stat">
                <div id="studentsCircle" class="hero-class-progress"></div>
                <p>students</p>
            </div>
            <div class="class-stat">
                <div id="tasksCirle" class="hero-class-progress"></div>
                <p>tasks</p>
            </div>

            <a :href="'/all-classes/' + last.content_name + '/' " class="button-resume"><p>Resume</p></a>

        </div>

    </div>

</template>

<script>

    module.exports = {
        data: function() {
            return {
                last:[]
            }   
        },
        mounted:  function() {

            axios.get('/custom_api/api_home_get.php?', {
                params: {
                  ID: 14
                }
              })
              .then(function (response) {
                this.last = response.data.currentCourses[0];
                console.log(response.data.currentCourses[0]);
              })
              .catch(function (error) {
                console.log(error);
              });

      }
    }
</script>

I'm wondering if this is something that can be achieved. How can I properly set the data last from the ajax call within the mounted method?

Answer №1

The this variable within the then function does not refer to the same context as your component, as in JavaScript, the this keyword is bound to its parent function.

To learn more about this concept, you can visit this link and see an example here.

To resolve this issue, there are a few methods you can use:

1 - Utilize the bind method of the Function prototype to bind the external this with the local this.

axios.get('/custom_api/api_home_get.php?', {
   params: {
     ID: 14
   }
})
.then(function (response) {
    this.last = response.data.currentCourses[0];
    console.log(response.data.currentCourses[0]);
}.bind(this))
.catch(function (error) {
    console.log(error);
});

2 - Employ ES6 arrow functions (which will achieve the same result as above)

axios.get('/custom_api/api_home_get.php?', {
   params: {
     ID: 14
   }
})
.then(response => {
    this.last = response.data.currentCourses[0];
    console.log(response.data.currentCourses[0]);
})
.catch(function (error) {
    console.log(error);
});

Answer №2

The issue lies with the usage of this in your .then(response) function. Dealing with this can be a complex concept, even for seasoned developers at times. Here's the root cause:

When you try to assign a value to a data property on the Vue component using this, you are actually referencing the axios.get() function rather than the component data. This happens because this is bound to the object or scope where it was called (the 'call-site'). Therefore, using this inside the function attempts to set a property that doesn't exist.

Possible solutions: Following the previous suggestion, chaining .bind(this) at the end of the promise may resolve this issue.

Another approach could be to use var that = this; to bind it within the mounted scope:

mounted: function() {
const that = this;

axios.get('url',  {
   // Insert code here
}).then(response) {
   const reply = response.data.currentCourses[0];
   that.last = reply;
   console.log("that.last: ", that.last, " | reply: ", reply);
}).catch(function(error) {
   // Additional code
});

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

unable to clear form fields after ajax submission issue persisting

After submitting via ajax, I am having trouble clearing form fields. Any help in checking my code and providing suggestions would be greatly appreciated. Here is the code snippet: jQuery(document).on('click', '.um-message-send:not(.disabled ...

Unable to subscribe due to the return value being an AnonymousSubject rather than an Observable

I am facing an issue in Angular 4 where I am attempting to retrieve details from a specific user when clicking on the 'user link profile'. However, I am unable to subscribe to my function because the return value of switchMap is AnonymousSubject ...

When using a custom AJAX function, make sure that bindings are functioning properly when setting properties within a callback in Ember

I've encountered some unexpected behavior while trying to set an Ember property inside a custom AJAX function callback. The AJAX function is triggered in the route, as seen in the code snippet below. The success callback updates the 'session.aja ...

In Redux, it is possible to add characters to an array but for some reason the remove action does not successfully reach the reducer

As a user types or erases characters, I am utilizing redux to update an array of characters. This allows me to set a success flag when the user correctly types the entire phrase. Currently, when typing in characters, the SET_INPUT action in redux fires of ...

Is there a way to apply an event function after adding elements through append?

When I click the button, a div is appended inside the body. However, I am trying to make it so that when I click on this newly appended div, an alert message pops up. I have tried implementing this with a highlighted area, but have been unsuccessful. How c ...

What is the process for storing form data into a text file?

Despite seeing similar questions in the past, I am determined to get to the bottom of why this code isn't functioning as expected. My goal is to input form data into a .txt file using a post request. While I lack extensive knowledge of PHP, I am pieci ...

Refreshing select2 dropdown options dynamically with AJAX updates

I have a select dropdown for locations that is initialized using select2 on page load. I am looking to dynamically update the data in the dropdown at regular intervals using ajax calls. However, when I attempt to update the data in select2, the dropdown ...

Executing HTTP Requests for Elements in an Array using JavaScript

I am currently struggling with a script that sends HTTP requests to a website in order to obtain various documents. The document IDs are stored within an array, and my intention is to send a request for each element in the array and return a unique message ...

How can I create a dropdown menu that is dependent on another dropdown menu using Ajax in my Laravel application?

I have two dropdown fields that are dependent on each other - Class & Section. I am trying to Select * from sections where class_id=selected Class Id. Although I attempted to achieve this using java script, it doesn't seem to work for me. Here are ...

transforming JSON information into tables on a webpage

Can someone help me with the challenge of incorporating a massive JSON file into an HTML table? I am encountering an issue where I continuously receive the error message Uncaught TypeError: v.forEach is not a function. Any guidance would be greatly appreci ...

Executing JavaScript functions when a browser tab is closed

When a user closes the browser tab, I want to call a specific JavaScript function. However, I only want this to occur when the user is actually closing the browser, not during page refreshes, link navigation, form submissions, or pressing the back button. ...

Guide for utilizing a table value as a parameter in a mySQL query with PHP

My website features an HTML table that is filled with data pulled from a mySQL table using PHP. Each row in the table is clickable, and when clicked, it opens a modal that contains a form to update and submit data back to the database using a mysql update ...

What is the best way to transmit a response using JSON instead of Jade?

//This is the code in my index.js file var express = require('express'); var router = express.Router(); /* Display the home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Movie Datab ...

Indentation differences between PHP and JavaScript

It's interesting to observe the different indentation conventions in various programming languages. Recently, I came across a code snippet from the PHP manual that caught my attention: switch ($i) { case "apple": echo "i is apple"; ...

What is the best way to create a mirrored effect for either a card or text using CSS

Can anyone assist me with this CSS issue? When I hover over to view the movie details, the entire word flips along with it. Is there a way to make only the word flip initially, and then have it return to normal when hovered? The HTML code is included belo ...

Accessing and playing audio files from Amazon S3 within Python code

I am attempting to directly read an audio file from S3 using Python. Initially, I record the audio with the following blob settings: blob = new Blob(audioChunks,{type: 'audio/wav'}); Then, I upload this file to S3 using Django: req=request.POST ...

Customizing Vue: Implementing an automatic addition of attributes to elements when using v-on:click directive

We are currently working with single file Vue components and we're facing a challenge in our mousemove event handler. We want to be able to determine if the target element is clickable. Within our Vue templates, we utilize v-on directives such as: v- ...

typescript: Imported modules in typescript are not functioning

I'm facing an issue where I installed the 'web-request' module but unable to get it working properly. Here is my code: npm install web-request After installation, I imported and used it in my class: import * as WebRequest from 'web-r ...

Access the configuration setting in the plugin settings for retrieving sales channel information

Is there a way to access specific values from the plugin configuration related to a particular sales channel? I'm trying to validate an API token, but can only retrieve the value set for all sales channels. I'm not sure how my custom admin compon ...

Tips for showcasing the latter portion of text within an HTML select dropdown menu

I have a select drop-down list with a fixed width of 80px, as shown in the image below: https://i.sstatic.net/pCpI9.png <select id="dd_country_code_2" name="dd_country_code_2" style="width: 120px; height: 23px;"> <option value="SEL">(Cou ...