所以我有以下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 许可协议
您的上下文正在发生变化:因为您正在使用关键字 function ,
this
在其范围内是匿名函数,而不是 vue 实例。请改用箭头功能。
注意: 顺便说一句,您应该继续在方法的顶层使用关键字 function (如示例所示),因为否则 Vue 无法将 vue 实例绑定到
this
。