Vue - 无法在promise中设置undefined的属性 [英] Vue - Cannot set property of undefined in promise

查看:139
本文介绍了Vue - 无法在promise中设置undefined的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下Vue文件:

So I have the following Vue file:

<template>

  <li class="notifications new">
      <a href="" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <sup>
          <span class="counter">0</span>
          </sup>
       </a>
       <div class="dropdown-menu notifications-dropdown-menu animated flipInX">
            <ul v-for="notification in notifications" @click="" class="notifications-container">
              <li>
                <div class="img-col">
                  <div class="img" style="background-image: url('assets/faces/3.jpg')"></div>
                </div>
              </li>
            </ul>
        </div>
  </li>

</template>

<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>

这个编译得很好,但是,在加载网页时,我收到以下错误:

This is compiling just fine, however, when loading up the web page, I get the following error:



app.js:1769 Uncaught(in promise)TypeError:无法设置未定义的属性'message' / p>

app.js:1769 Uncaught (in promise) TypeError: Cannot set property 'message' of undefined


我试图创建另一种方法,但没有任何乐趣。我似乎无法解决为什么这个在这里无法访问。

I have tried to create another method as well, but had no joy. I literally cannot seem to work out why this wouldn't be accessible here.

推荐答案

您的上下文正在发生变化:因为您使用的是关键字 function 在其范围内是匿名函数,而不是vue实例。

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

请改用箭头函数。

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

    },

NB:你应该顺便说一下,继续使用关键字 function 作为方法的顶层(如示例所示),因为否则Vue无法将vue实例绑定到 this

NB: You should by the way continue to use the keyword function for the top level of your methods (as shown in the example), because otherwise Vue can't bind the vue instance to this.

这篇关于Vue - 无法在promise中设置undefined的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆