Vuejs Promise中读取属性undefined

1个月前 87次点击 来自 前端

原文链接:Vue - Cannot set property of undefined in promise

原作者脚本

<script>
export default {

    data: function() {
        return {
          notifications: [],
          message: "",
        }
    },

    methods: {

        loadData: function() {
            Vue.http.get('/notifications').then(function(response) {

                console.log(response.data);
                //this.notifications = response.data;
                //this.notifications.push(response.data);

                this.message = "This is a message";

                console.log(this.message);
            });

        },
    },

    mounted() {
        this.loadData();
    },

}

</script>

解决方案使用箭头函数替代关键字函数,原因如下:

Your context is changing: because you are using the keyword function, this is inside its scope the anonymous function, not the vue instance.

Use arrow function instead.

  loadData: function() {
        Vue.http.get('/notifications').then((response) => {

            console.log(response.data);
            //this.notifications = response.data;
            //this.notifications.push(response.data);

            this.message = "This is a message";

            console.log(this.message);
        });

    },

基于以上原因,故而也可以通过:
https://stackoverflow.com/a/54735994
One can set this to a const outside the code block and use that const value to access the class properties.

const self = this;

blockMethod(function(data) {
    self.prop = data.val();
})

不过一般更通用的写法是:

var that = this;

blockMethod(function(data) {
    that.prop = data.val();
})

在微信小程序开发中,var that =this的声明很常见,其原因也是一样的,通过一个变量保存this的作用域。

不过在Vuejs的开发中还是使用箭头函数的写法更合适。

Card image cap
开发者雷

尘世间一个小小的开发者,每天增加一些无聊的知识,就不会无聊了

要加油~~~

技术文档 >> 系列应用 >>
热推应用
Let'sLearnSwift
学习Swift的入门教程
PyPie
Python is as good as Pie
标签