【问题标题】:Vue2 object not setted未设置 Vue2 对象
【发布时间】:2017-01-25 12:07:49
【问题描述】:

我正在尝试从服务器获取数据列表并显示它,但看起来 Vue 看不到新数据(不让它们反应)

      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",
});

我也尝试使用

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

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

但它仍然不适合我。感谢您的帮助!

【问题讨论】:

    标签: javascript vuejs2 vue-component


    【解决方案1】:

    您在 thencatch 回调中丢失了上下文。结果,您设置了window.videos 变量(全局)而不是您的组件实例videos 属性(与error 相同)。

    简单的解决方法是使用保留词法绑定的arrow functions

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

    【讨论】:

    • 谢谢帮助。但是为什么没有 ES2015 响应我就不能写它=> ???来自 axios 文档axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
    • 因为当你使用匿名函数function (response) { console.log(response); }时,执行上下文是全局对象(window)。如果你想console.log 很好,但在你的情况下你想设置你的组件的属性,所以你需要有正确的this.then(function (response) { this.videos = response.data.videos; }.bind(this)) 会工作。或者您也可以保存对此的引用并在回调中使用它:const self = this; ... .then(function (response) { self.videos = response.data.videos; })
    猜你喜欢
    • 2013-04-24
    • 2023-03-12
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多