1

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!

1 Answer 1

1

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;
        })
    },
},
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks it help. But why I can't write it without that ES2015 response => ??? from axios docs axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Because when you use anonymous function function (response) { console.log(response); } execution context is global object (window). It's fine if you want to console.log, but in your case you want to set property of your component, so you need to have proper this. .then(function (response) { this.videos = response.data.videos; }.bind(this)) would work. Or you could also save reference to this and use it inside callback: const self = this; ... .then(function (response) { self.videos = response.data.videos; }).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.