"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

When accessing a method exposed in Angular2 from an external application, the binding changes are lost

In my code, I have a method that is made public and accessible through the window object. This method interacts with a Component and updates a variable in the template. However, even after changing the value of the variable, the *ngIf() directive does not ...

Learn the process of eliminating a class utilizing this JavaScript function

This script is designed to identify and manipulate elements with the class menu-option-set. When an element within this class is clicked, it adds the class "selected" to that specific element while removing it from all others in the list. My goal is to en ...

Establish a connection between the MySql database in WHM (phpmyadmin) and a node.js application

Our team has been working on setting up the database connection with Mysql using node.js in Cpanel. Although I didn't create the database myself, I have all the necessary information such as the host, user, password, name of the database, and port nu ...

Can this functionality be accomplished using only HTML and CSS, without relying on JavaScript?

Image for the Question Is it possible to create a zoom functionality using only HTML and CSS, without relying on JavaScript? I need this feature for a specific project that doesn't support JavaScript. ...

Deliver data in batches of ten when the endpoint is accessed

I am currently in the process of developing a web application using Next.JS and Node. As part of this project, I have created my own API with Node that is being requested by Next.JS. One particular endpoint within my API sends data to the front end as an ...

Exploring the depths of Vue.js routing through nesting

My Current Route is function route(path, view) { return { path: path, meta: meta[path], component: resolve => import(`pages/${view}View.vue`).then(resolve) } } route('/', 'Home'), route('/help', 'Help ...

How can AngularJS handle uploading multipart form data along with a file?

Although I am new to angular.js, I have a solid understanding of the fundamentals. My goal is to upload both a file and some form data as multipart form data. I've learned that this is not a built-in feature of angular, but third-party libraries can ...

To utilize this.<module> within a Nuxt plugin, simply access it

How can I access a JS API exposed by a Nuxt module from a client-side plugin? Situation: I am utilizing Buefy/Bulma, which is implemented in nuxt.config.js like this: modules: [ ['nuxt-buefy', {css: false}], ], Buefy provides this.$buefy.&l ...

Text field suddenly loses focus upon entering a single character

In my current code, I have functions that determine whether to display a TextField or a Select component based on a JSON value being Text or Select. However, I am facing an issue where I can only enter one letter into the TextField before losing focus. Sub ...

How can you extract elements from a JSON array into separate variables based on a specific property value within each element?

In the following JSON array, each item has a category property that determines its grouping. I need to split this array into separate JSON arrays based on the category property of each item. The goal is to extract all items with the category set to person ...

Tips for switching the background image in React while a page is loading?

Is there a way to automatically change the background of a page when it loads, instead of requiring a button click? import img1 from '../images/img1.jpg'; import img2 from '../images/img2.jpg'; import img3 from '../images/img3.jpg& ...

Dealing with a passed EJS variable in string form

When working with passed data in ejs, I usually handle it like this and it works perfectly: let parsed_json = JSON.parse('<%-JSON.stringify(passed_data)%>'); However, I encountered a problem when trying to dynamically pass a string variabl ...

Is it possible to use null and Infinity interchangeably in JavaScript?

I've declared a default options object with a max set to Infinity: let RANGE_DEFAULT_OPTIONS: any = { min: 0, max: Infinity }; console.log(RANGE_DEFAULT_OPTIONS); // {min: 0, max: null} Surprisingly, when the RANGE_DEFAULT_OPTIONS object is logged, i ...

Exploring the world of Vue.js object mapping

I currently have the following object: data: () => ({ customer: { item: { name: undefined }} }) This object is being used in the template as follows: <v-number separator="." decimal="2" ...

The scope of a JS array is being lost in Firebase

The Firebase data structure looks like this: -users --demo1 ---conid:1 -election --election1 ---conRegex:1 --election2 ---conRegex:1 Here is the code to retrieve election1 and election2: var conid; var conRegex; var electionArr = []; if(uidA ...

What is the best way to incorporate arrow buttons on my website in order to unveil various sections on the homepage?

A colleague and I are collaborating on a website for his cookery business. He has sketched out some design ideas on paper, one of which involves having a homepage with 4 different sections stacked on top of each other. Each section would have an arrow butt ...

express-validator: bypass additional validation in a user-defined validator

Utilizing the express-validator package for validating my request data. As per the documentation, we need to declare them in this manner: app.use(expressValidator({ customValidators: { isArray: function(value) { return Array.isArray(value); ...

The functionality of the controls is not functioning properly when attempting to play a video after clicking on an image in HTML5

While working with two HTML5 videos, I encountered an issue with the play/pause functionality. Despite writing Javascript code to control this, clicking on one video's poster sometimes results in the other video playing instead. This inconsistency is ...

Steps to send an object array using a promise

I've put in a lot of effort but haven't found a solution that works well for me. I attempted using promise.all and setting the array globally, but it didn't work out. My goal is to search through three MongoDB collections, match the finds, ...

Set a timer to run only during particular hours of the day, and pause until the next designated time

I need assistance with integrating a function called "tweeter" into my code so that it runs at specific times throughout the day - 09:00, 13:00, 17:00, and 21:00. Currently, the function runs continuously after the initial hour check is completed, instead ...