Vue - 无法在承诺中设置未定义的属性

新手上路,请多包涵

所以我有以下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: Cannot set property ‘message’ of undefined

我也尝试过创建另一种方法,但没有任何乐趣。我似乎无法弄清楚为什么在这里无法访问 this

原文由 Phorce 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 532
2 个回答

您的上下文正在发生变化:因为您正在使用关键字 functionthis 在其范围内是匿名函数,而不是 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);
        });

    },

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

原文由 FitzFish 发布,翻译遵循 CC BY-SA 3.0 许可协议

可以在代码块之外将 this 设置为 const 并使用该常量值来访问类属性。

IE

 const self = this;

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

原文由 sese smith 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题