twigg
twigg

Reputation: 3993

vuejs v2.0 pass data to component

I built an app on Laravel 5.3 using vue.js and im starting to move over to vue.js to make the pages dynamic. I got everything working on a single page so want to convert that over to a component but after doing so I get the following error:

[Vue warn]: Error when rendering component <homepage> at C:\xampp\htdocs\....... 
TypeError: Cannot read property 'nxt_weekly' of undefined

I was passing data to the view like so:

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

mounted: function () {
    this.fetchEvents();
},

data: {
    loading: true,
    stats: []
},

methods: {
    fetchEvents: function () {
        this.$http.get('home/data').then(function (response) {
            this.stats = response.body;
            this.loading = false;
        }, function (error) {
            console.log(error);
        });
    }

});

In stats[] is where I hold the JSON response from the API and then call them all in my view like so:

<span class="stat" v-text="'stats.nxt_today'"></span>
....
....

This works but when I switch over to creating a component the errors listed above show, my new code is:

Vue.component('homepage', require('./components/Homepage.vue'),{

    mounted: function () {
        this.fetchEvents();
    },

    data: function () {
        return{
            loading: true,
            stats: []
        }
    },


    methods: {
        fetchEvents: function () {
            console.log('running here');
            this.$http.get('home/data').then(function (response) {
                this.stats = response.body;
                this.loading = false;
            }, function (error) {
                console.log(error);
            });
        }
    }
});

What am I doing wrong? How come my stats[] object is now empty when the component is trying to access it?

Upvotes: 5

Views: 8268

Answers (1)

Mani Jagadeesan
Mani Jagadeesan

Reputation: 24265

You need to pass your stats as a property to the component using v-bind, as shown below:

<homepage v-bind:stats="stats"></homepage>

The above needs to be done in your root template. And in your homepage component, you can receive the value in props as follows:

Vue.component('homepage', {
    props: ["stats"],
    mounted: function () {
        // ...
    },
    // ...
}

Within the template of this component, you will be able to access stats.nxt_today normally.

By the way, is your stats an array or an object? You have defined it as an empty array initially, but accessing it as an object.

If you still have issues, you can use vue-devtools to view all the objects available within a component.

Upvotes: 9

Related Questions