当我想将API结果中的值发送到数据时出现错误,错误是这样的
Uncaught (in promise) TypeError: Cannot set property 'notification' of undefined at eval (HeaderPortal.vue?070f:367)
Run Code Online (Sandbox Code Playgroud)
这是我的HeaderPortal.vue
data() {
return {
notification: []
}
}
mounted: {
const res = this.GET('/api/v2/notification', 'BEARER', null).then(function(res) {
console.log(JSON.parse(res))
this.notification = JSON.parse(res);
});
}
Run Code Online (Sandbox Code Playgroud)
this.GET 来自这里
methods: {
async GET(url, headers, callback) {
const options = headers === 'BASIC' ? HEADERS_BASIC : HEADERS_BEARER;
try {
const response = await axios.get(`${BASE_URL}${url}`, options);
return (JSON.stringify(response));
} catch (e) {
console.error(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
怎么处理?我的代码有问题吗?
Flo*_*las 12
如果您需要访问this关键字,请确保在回调中使用箭头函数() => {}而不是常规函数。function() {}如果不这样做,this关键字将适合undefined您的情况。这就是为什么您尝试在第一个代码片段中进行设置时会出现错误this.notification = JSON.parse(res);。
您的第一个代码片段有点奇怪,也许您忘记复制某些内容?您的代码不应直接位于方法对象内部。它应该位于已安装的挂钩中,或者位于第二个片段中的正确方法中。
| 归档时间: |
|
| 查看次数: |
18473 次 |
| 最近记录: |