Creating reactive data in a Vue.js 2 component

I'm currently learning Vue.js 2. I encountered an issue with my code while receiving dynamic data from a server (using Laravel 5.3). The problem arises when I attempt to declare the users array within the component instead of declaring it in the Vue() instance, where it works perfectly:

HTML:

<div id="app">
    <my-component>
        <ul id="users-list">
            <li v-for="user in users">{{user.name}}</li>
        </ul>
    </my-component>
</div>

JS:

Vue.component('my-component', {
    template: '#users-list',
    data: function () {
        return {
            users: []
        }
    },
    mounted: function() {
        this.$http.get('http://127.0.0.1:8003/api/test').then((response) => {
            console.log(response.body);
            this.users = response.body;
        }, function() {
            alert('brrh');
        });
    }
});
new Vue({
    el: '#app',
});

An error message is shown as: "Uncaught ReferenceError: users is not defined"

Answer №1

If you're attempting to implement an inline-template, make sure to add the directive to your <my-component> call.

    <div id="app">
            <my-component inline-template>
                    <ul id="users-list">
                            <li v-for="user in users">{{user.name}}</li>
                    </ul>
            </my-component>
    </div>

Additionally, ensure that you remove the template parameter from your component call as shown below:

    Vue.component('my-component', {
        data: function () {
            return {
                users: []
            }
        },
        mounted: function() {
            this.$http.get('http://127.0.0.1:8003/api/test').then((response) => {
                console.log(response.body);
                this.users = response.body;
            }, function() {
                alert('brrh');
            });
        }
    });

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

Check out this jsFiddle link for reference.

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

Guide on incorporating Admin LTE 3 into Nuxt.js

Is there a way to seamlessly combine adminlte 3 with Nuxt.js? Following the installation of adminlte 3 via npm, I attempted to add css and js files in nuxt.config.js. While the styles appear to be functioning correctly, the javascript is not executing as ...

Do not proceed with the form submission if the fields are left blank

I am facing a challenge with organizing two sets of data, "heat" and "cold", obtained from an external provider. The data is messy and I have trimmed down the code to focus on the main issue at hand. Both "heat" and "cold" have properties that users need t ...

Configuring a JavaScript calendar with custom margins

Having trouble selecting a date with the Bootstrap datepicker class. After running the snippet, the calendar appears below the textbox: <input type="text" class="form-control datepicker" name="due_date" id="due_date" onclick="calendar_up()" value="" pl ...

I'm unsure of the most efficient way to condense this statement

$(document).ready(function(){ if ($(window).width() <961){ $('.item').on('click',function(){ /*---do something---*/ }) }else{ $('.item').on('click',function(){ ...

Is it possible to include number padding in a Bootstrap number input field?

When using an input box like this: <input type="number" class="form-control" value="00001" /> Is there a way to make it so that when the arrow up key is pressed, it changes to 00002 instead of just 2? https://i.sstati ...

Is it necessary to have both index.js and Component.js files for a single component in React?

Continuously analyzing various projects, I often come across authors who organize their file structures in ways that are perplexing to me without proper explanation. Take, for instance, a component where there is a folder named Header. Inside this folder, ...

"Using the push method in JavaScript allows for the combination of arrays rather than

Looking to retrieve data from an API and store it in an array. When I assign the value directly using '=', the desired data is displayed. However, when attempting to add elements using 'push', they are added as another array. Below is ...

Show more/less of the text snippet and main body of information

I am currently in the process of setting up a basic WordPress blog with only one page dedicated to the blog archive. However, I have encountered an issue. I want to implement a toggle functionality that allows visitors to easily navigate through posts on t ...

Exploring the intricacies of React Router parameters

I have been facing some issues with my routing setup. Specifically, I have a static route called list and a dynamic route called user/:id. The problem arises when navigating between these two pages. (1) Whenever I navigate to the list route from the user/: ...

Translating SQL to Sequelize Syntax

I have an SQL query that I need to rewrite as a sequelize.js query in node.js. SELECT historyTable1.* FROM table1 historyTable1 WHERE NOT EXISTS ( SELECT * FROM table1 historyTable2 WHERE historyTable2.id=historyTable1.id AND historyTable2.da ...

Clearing the filename in a file type input field using React

When using this input field, only video files are accepted. If any other types of files are uploaded by enabling the "all files" option, an alert will be displayed. While this functionality is working correctly, a problem arises if a non-video file is adde ...

Issue with Bootstrap flash alert CSS on mobile devices is not functioning properly

I am in the process of developing a Rails application. Within my app, I utilize Bootstrap's CSS for displaying flash messages on alerts. Instead of fully incorporating Bootstrap's CSS, I only integrate styles related to alerts in order to prevent ...

Attempting to clear the value of a state property using the delete method is proving to be ineffective

Within my React-component, there exists an optional property. Depending on whether this property is set or not, a modal dialog is displayed. Therefore, when the modal should be closed/hidden, the property must not be set. My state (in simplified form): i ...

Trouble getting AngularJS $scope arrays to populate with multiple PHP to MySQL queries

In my Angular controller, I used to fetch data from a PHP file that pulled one query from the database, stored it in a scope array, and displayed it on the webpage successfully. However, now I am trying to execute two queries in the same file. Each query ...

How can I access and retrieve a local variable using geolocation in HTML5 and the Google Maps API?

Seeking assistance with a coding dilemma: I need to retrieve the geolocation position for use in my calcRoute function. The goal is to set the geolocation as the starting point. Below is the code snippet: function calcRoute(){ var pos; navigator.g ...

Transform the assurance into a JSON entity

Currently facing an issue with converting the promise returned by the service to the controller. My goal is to generate an array of JSON objects using the data within the promise. In the controller, this is what I'm receiving: https://i.stack.imgur.co ...

Leveraging *ngFor to extract HTML content from ion-label

I've encountered an issue while using *ngFor in my HTML like this: <ion-slides #slides [options]="slideOpts"> <ion-slide class="numbers-wrapper" *ngFor="let questionNumber of numbers" (click)="clickQue ...

What is the best way to include numerous optional parameters within a single route in Express?

Been a huge fan of Stackoverflow and finally decided to ask my first question here! I've been working on a JavaScript Express project, trying to figure out if it's possible to achieve the desired functionality under a single GET request. Struggli ...

Implementing component method calls in store.js

In my Login.vue component, I have a method called postData() postData() { this.$store.dispatch('doLogin', fdata) }, The doLogin method is located in store.js actions: { doLogin({ commit }, loginData) { commit('loginStart ...

Error message in node.bcrypt.js: 'No callback function provided; result is undefined.'

Currently, I am enrolled in Mosh Hamdani's Mastering React Course and have encountered some challenges with back-end development. The most recent issue is an error message stating: “undefined No callback function was given” when attempting to regi ...