issue with accessing property in vue 2 simple examination

Hey there! I'm currently working on implementing Vue in a Laravel application, but I've run into some challenges. Essentially, my goal is to retrieve data from a GET request and generate results based on that data. However, I'm struggling to successfully store the retrieved data in an array variable. Let me elaborate:

In my app.js file, I initialize my Vue instance like this:

Vue.component('search', require('./components/search.vue'));

const app = new Vue({
   el: '#app',
});

Then, in my main.blade.php file, I include my Vue component as follows:

<search class="row expanded container"></search>

Below is the content of my Vue file:

<template>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Example Component</div>

                    <div class="panel-body">
                        I'm an example component!

                        {{test}}

                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {

    data () {
        return {
            test:"this is my sample",
            results: []
        }
    },

    mounted () {
        console.log(this); // object exists here  
        console.log('Component mounted.') // works fine
        axios.get("http://localhost:8000/api/search?q=qwfqw")
        .then((resp) => {
            if(typeof resp.data === 'string') {
                resp.data = JSON.parse(resp.data);
            }
            console.log(resp.data); // object exists here
            this.results = resp.data;
        }).catch(err => {
            console.error(err);
        });
    }
}


</script>

The page loads without any issues, but I encounter an error stating that the "results" variable is undefined. Can anyone guide me on how to properly populate the "results" variable with the fetched data from the GET request? What would be the correct approach to achieve this?

Answer №1

One issue to consider is scoping. Within your code, the this keyword inside the callback function refers to the function itself rather than the Vue instance, resulting in it being undefined. To fix this, you can utilize an arrow function (assuming Laravel has ES6 properly set up) to ensure that this points to the Vue instance:

axios.get("http://localhost:8000/api/search?q=qwfqw")
    .then(resp => {
        if(typeof resp.data == 'string') {
            resp.data = JSON.parse(resp.data);
        }
        console.log(resp.data); // at this point, the object exists
        this.results = resp.data;
    });

Answer №2

this in JavaScript is determined by what is called the function and not where it is defined. To resolve this issue, one approach is to store a reference to this in another variable using var self = this;, and then use that variable to reference the results like self.results = resp.data;

Alternatively, you can utilize the bind function or Arrow functions. With arrow functions, the scope of this changes to where it is defined lexically.

mounted () {
        var self = this;
        console.log(this); // here my obj exists  
        console.log('Component mounted.') // it works
        axios.get("http://localhost:8000/api/search?q=qwfqw")
        .then(function(resp){
            if(typeof resp.data == 'string') {
                resp.data = JSON.parse(resp.data);
            }
            console.log(resp.data); // here the object exists
            self.results = resp.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 request for JSON parsing encountered a failed attempt, resulting in an error while trying to parse the JSON

var userData = { "emailAddress": document.getElementById('emailAddress').value, "password": document.getElementById('password').value } var userDataString = JSON.stringify(userData); alert(userDataString); var url = "url"; var ...

JavaScript causing Axios network error

Recently, I've started exploring the combination of axios and stripe in my project but unfortunately, I have encountered some challenges. Whenever I attempt to initiate a post request using axios, an error pops up which looks like this: https://i.sta ...

Issues with Three.js materials not rendering properly when loading .obj and .mtl files

I recently downloaded a free 3D model and I'm attempting to view it using three.js. Although the model is loading correctly, there seems to be an issue with the materials not loading properly. Strangely enough, only the wine bottles behind the bar are ...

How to get the total number of rows/records in a JSON store using ExtJS?

My dilemma involves a JSON store that provides data in JSON format. I am currently attempting to determine the number of rows or records in the JSON string. However, when utilizing the store.getCount() function, it consistently returns 0. Strangely, the ...

Generate an interactive table: one segment featuring a title or tag - its corresponding rows and columns that change dynamically, followed by another similar segment

I'm attempting to generate a dynamic table with the following structure upon clicking a button (I can't include an image, so here is a sample code to illustrate what I'm aiming for, but I need everything to be dynamic in the actual scenario) ...

The process of uploading a React App to Heroku resulted in a critical error: "FATAL ERROR: Heap limit reached, Allocation failed - JavaScript heap out of memory."

There's a puzzling issue that I believe I have the solution to (paying for more bandwidth on Heroku), but the root of the problem eludes me and it's truly frustrating. Any assistance in pinpointing the cause would be greatly appreciated! Hopefull ...

Choosing between radio buttons either horizontally or vertically within a table

Here is the markup I am working with: <table> <tr> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></ ...

How to Remove Carousel Arrows in Bootstrap 5

Any suggestions on how to remove the previous and next arrows in a Bootstrap carousel, particularly on the first and last slide? I'm struggling to find a solution for Bootstrap 5 as most solutions available are for older versions. Your help would be g ...

Determining the current directory and file name in React and Webpack

Currently, I am working on a react js project and utilizing webpack and redux. Below is the organization of folders in my project: -assets -src -component -index.jsx -container -index.jsx My goal is to assign dynamic className to the inde ...

What is the best method for developing a live text display switcher that works across different pages?

Hello everyone! I am currently in the process of creating a display toggler for my website. I have two separate pages, index.html and toggler.html. In index.html, the "TEXT" is displayed, while toggler.html contains the actual toggler or switch button. Whe ...

Using Ajax to send data from a parent JSP to a child JSP and then refresh the page

Can anyone assist me in resolving my issue? I'm attempting to incorporate an existing JSP partial (child) into another JSP page (parent). These pages are controlled by Java Controller classes in a Weblogic 12c environment using Spring. The child JSP i ...

Utilizing React Classes for File Organization in Three.js

I have successfully created a three.js application, but I am facing a challenge in organizing my functions into separate files. There is a specific mesh function that I would like to store in its own dedicated file. Here are my functions: componentDidMo ...

Is it possible to use getJSON to retrieve a value from an HTML tag ID that has already been displayed on a webpage? How about using json_decode

Is there a way to retrieve the value using the HTML tag ID after an HTML page has been rendered? For example, how can I access the date value using the td_date in my JavaScript function? Below is the code snippet that populates the data on the page: listS ...

Retrieve the value of a related object based on the user's click

Check out this sample code on JSFiddle <a href="#"></a> <a href="#"></a> <a href="#"></a> <a href="#"></a> <div></div> JavaScript: function Product(name, price){ this.name = name; this. ...

Traversing through nested arrays within nested objects using AngularJS

In my project, I am utilizing angularjs 1 and dealing with a complex json object that has multiple levels of nesting. My goal is to use ng-repeat in order to access a nested array within the json structure. [{ "information": { "name": "simdi jinki ...

Creating a table in React.js by mapping array data from console.log output

I am working with an API that returns an array of results when called using axios.get(). I am trying to map this array into a table in a React JS application. Here is the code for fetching data from the API: const [data, getData] = useState([]) u ...

Tips for transferring a list via ajax to a controller

Having a controller as follows.. public ActionResult Report(List<string> invoiceIds) and utilizing an ajax call like this... function generateAccountsPayableReports() { var ms = $("#msInvoicesAPV").data("kendoMultiSelect"); var invoices = ...

The function req.checkBody does not exist

Currently, I am following the guidance of the Mozilla Express tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/forms). However, as I reached the section involving express-validator, I encountered a persistent error messag ...

Issues with expanding all nodes in the Angular Treeview function by Nick Perkins in London are causing difficulties

Currently utilizing the angular treeview project found here: https://github.com/nickperkinslondon/angular-bootstrap-nav-tree After examining the functionality, it seems that this treeview is lacking search capabilities. To address this limitation, I deci ...

Retrieve information from subcategories in the Realtime Database using Firebase

Trying to access message inputs from ALL users has been a challenge. While it can be done for a specific user, the goal is to do so for all users by specifying in the code. Each UID is unique, adding complexity to the process. The Realtime Database struct ...