"Encountering a Problem with Assigning Variables in Vue

My issue revolves around the integration of VueJs, Vue-Resource, and Laravel.

The problem occurs when attempting to assign a local variable to response data received from an AJAX request using vue-resource.

Code

Javascript

<script>
        flags_page = new Vue({

            el: '#body',

            data: {
                retrievedFlags: {},
                chosenFlag: ''
            },

            ready: function () {
                this.getFlagTypes();
            },
            methods: {
                getFlagTypes: function(){

                    this.$http.get('/getFlags=' + '{{ $id }}', function(data){

                        //Issue lies on this line
                        this.retrievedFlags = data.retrievedFlags;

                    })
                }
            }
        });
    </script>

PHP

public function getFlags($type)
   {
    $flags       = Flags::all();

    return [
        'retrievedFlags' => $flags,
        'chosenFlag' => $type,
    ];
}

ERROR

vue.min.js:7 Uncaught TypeError: Cannot read property 'get' of undefined
    at new n (vue.min.js:7)
    at r._bind (vue.min.js:8)
    at n (vue.min.js:6)
    at vue.min.js:6
    at new n (vue.min.js:6)
    at n.create (vue.min.js:6)
    at r.create (vue.min.js:6)
    at r.diff (vue.min.js:6)
    at r.update (vue.min.js:6)
    at n.update._update (vue.min.js:8)

Despite numerous changes made, I am still unable to identify the root cause of this error. It is puzzling as other similar pages function correctly with the same logic.

It is interesting to note that when I console.log() the returned data object, it displays perfectly fine. However, once an attempt is made to assign it to a variable, the error surfaces.

In addition, VueJS and Vue-Resource are both locally included in the project.

Screenshot of my console.log(this): https://i.stack.imgur.com/YaAvR.jpg

Answer №1

The Resolution

Here's the fix: instead of

:checked="{flag.name == chosenFlag}"
, use
:checked="flag.name == chosenFlag"

The Clarification

The issue wasn't with the code provided, but rather with how I handled a variable assignment after an ajax request using Vue-Resource.

When @apokryfos suggested I console.log(this) before my this.$http.get function, I found that the data was indeed being set, as evidenced here: https://i.stack.imgur.com/EjRqw.jpg

Upon debugging the HTML rendering code, I discovered that the problem stemmed from this section:

<div class="mt-checkbox-inline">
    <div class="col-md-1" v-for="flag in retrievedFlags">
        <label>
            <input type="checkbox" :checked="{flag.name == chosenFlag}" value="@{{ flag.name }}"> @{{ flag.name }}
        </label>
    </div>
</div>

To resolve the error, I removed the curly braces from the :checked="" attribute. While the Vue.js documentation suggested using the curly braces, it turned out to be causing the issue. It's possible that my Vue.js version played a role in this confusion, potentially leading others astray in their attempt to assist me.

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

Struggling to decide on the perfect CSS selector for my puppeteer script

I am trying to use puppeteer page.type with a CSS selector. <div class="preloader"> <div class="cssload-speeding-wheel"></div> </div> <section id="wrapper" class="login-register"> <div class="login-box"> <d ...

Vue2Leaflet does not seem to be able to place a custom icon on the map

I've attempted numerous examples, but all I get are broken images or default icons <l-marker v-for="marker in getFilteredVehicles" :lat-lng="marker.latLng" :key="marker.rtoNo" @click="o ...

Trouble in sending email with attachment using Microsoft Graph

I have been working on an application that has the functionality to send emails from a User, following the guidelines provided in this article. Despite everything else functioning correctly, I'm facing an issue when trying to include attachments. The ...

Tips for preventing the "Error: Avoided redundant navigation to current location: "/inside/home" when the authentication guard restricts access to the route

Upon logging out, I would like Vue to automatically navigate to the default landing page. The current behavior is causing Vue to redirect to the existing route instead. This redirection gets intercepted by a guard that prevents it and sends the user back ...

Execute function prior to redirection of iframe

I have a specific challenge with an iframe on my webpage. I am looking to trigger a function right before the iframe reloads a new page, rather than after it has finished loading. I need this function to be triggered before the iframe redirects to the new ...

Setting up Swiper in a ReactJS environment

I've been trying to incorporate Swiper for a slider in my React application, but it's not behaving as expected. Here's what I did: npm install Swiper Then I imported Swiper in the componentDidMount method of my component like this: import ...

Insert a CSS Class into an HTML div element with JQuery

I'm faced with a bit of a challenge. Here's the scenario: <div class="portItem"></div> <div class="portItem"></div> <div class="portItem"></div> <div class="p ...

What strategy should be employed to ensure that Javascript is operational upon completion of page loading?

I'm facing a challenge with running my JavaScript on my ASP.NET webform page. It seems like the elements are not fully loaded when the script runs, which could be causing issues. How can I use jQuery to ensure that my script is placed at the bottom of ...

Unable to execute application due to invalid element type

I'm just diving into learning React Native, and as I attempt to launch my app, an error message pops up: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Verif ...

Utilizing a MONGO_URL to efficiently run multiple Meteor applications on a single server

I have successfully deployed a Meteor application on my Ubuntu server using Meteor Up (MUP) and everything is working well. However, when attempting to deploy a second app on the same server, I encounter issues with connecting to MongoDB. The error message ...

Tips for determining if an HTMLElement has already been created

One issue I'm facing is with a third party component that emits an "onCellEdit" event and passes a cell element as a parameter. My goal is to automatically select the entire text in the input element generated inside this cell when the event occurs. ...

Review a roster of websites every half a minute (Revise pages every half an hour??)

Just starting out with HTML coding! Can someone please provide the code that will allow me to save various webpages and automatically cycle through them every 30 seconds? And also ensure that the webpages are updated every 30 minutes. ...

What is the best way to transfer state information from a hook to be displayed in the App component in React

Is there a way to transfer the state(data) of info to the App hook, in order to showcase the properties within div elements? The function setInfo(info) saves the data intended for display on the Map hook and inspecting console.log(info) within _onClick rev ...

Retrieve the value of a nested JSON object using the name of an HTML form field, without the use of eval

I am facing a similar issue to Convert an HTML form field to a JSON object with inner objects, but in the opposite direction. Here is the JSON Object response received from the server: { company : "ACME, INC.", contact : { firstname : "Da ...

What is the method for expanding this schema array using mongoose?

In the user schema below, I'm focusing on updating the ToDo section under User.js. My goal is to include new data to an array within the database. data.js app.post("/data", loggedIn, async (req, res) => { console.log(req.body.content); ...

The API call for /api/users/create was resolved without a response, which could potentially lead to requests getting stuck. This issue was detected in

I've developed an API endpoint to manage user account creation within my Next.js application, utilizing knex.js for handling queries. Despite this, I keep encountering the following error: API resolved without sending a response for /api/users/create ...

What is the syntax for accessing a nested object within the .find method?

Currently building an application in node.js. I am struggling with referencing the "email" element in the "userData" object within the Order model when using the find method. Any suggestions on how to properly refer to it? Order model: const orderSchema = ...

Error message: "The getJSON call is missing a semicolon before the statement."

Can someone please explain the following. I've been searching online for a long time trying to find assistance and I think I am following all the correct steps but still receiving errors. Here is the script in question on my webpage: function GetPag ...

How can I display several custom markers that are constantly updating on a Google map with MySQL and PHP?

Currently, I am using the following code to generate markers on a Google map by retrieving data from a database. However, the issue I am facing is that it only generates one marker instead of all the markers stored in the database. & ...

Top replacements for jQuery in AngularJS applications

It would be great to compile a comprehensive list of jQuery alternatives that are compatible with AngularJS, capable of manipulating styles (css), and supporting effects like fadeIn, fadeOut, slideDown, slideUp, etc. Based on feedback from comments, we sh ...