Bogdan  Dubyk
Bogdan Dubyk

Reputation: 5564

Vue2 object not setted

I'm trying to get list of data from server and show it, but looks like Vue do not see new data(not make them reactive)

      Vue.component('Videos', {
            template:
                `
                <div>
                    <div v-for="video in videos" v-text="video.name">
                    </div>
                <div>
            `,
            data() {
                return {
                    videos: {},
                }
            },
            methods: {
                getVideos() {
                    axios.get('/admin/videos?token='+localStorage.getItem('auth_token'))
                        .then(function(response) {
                            this.videos = response.data.videos;
                        }).catch(function(errors){
                            this.error = errors.data;
                    })
                },
            },
            created: function () {
                this.getVideos();
            }

        });

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

Also I try to use

Object.keys(response.data.videos).forEach( key => this.$set(this.videos, key, response.data.videos[key]) );

and this.videos = Object.assign({}, this.videos, response.data.videos)

but it's still not work for me. Thanks for helping!

Upvotes: 1

Views: 64

Answers (1)

dfsq
dfsq

Reputation: 193301

You are loosing context in both then and catch callbacks. As the result, you are setting window.videos variable (global) instead of your component instance videos property (same with error).

Simple fix is to use arrow functions which preserve lexical binding:

methods: {
    getVideos() {
        axios.get('/admin/videos?token='+localStorage.getItem('auth_token'))
            .then(response => {
                this.videos = response.data.videos;
            }).catch(errors => {
                this.error = errors.data;
        })
    },
},

Upvotes: 1

Related Questions