首页 文章

Vue - 无法在promise中设置undefined的属性

提问于
浏览
5

所以我有以下Vue文件:

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

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

app.js:1769 Uncaught(in promise)TypeError:无法设置undefined的属性'message'

我也试图创造另一种方法,但没有快乐 . 我似乎无法解决为什么 this 在这里无法访问 .

1 回答

  • 24

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

    请改用箭头功能 .

    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: 顺便说一句,你应该继续使用关键字函数作为方法的顶层(如示例所示),因为否则Vue无法将vue实例绑定到 this .

相关问题