vue.js - 从rest api vue中获取
问题描述
我可能有点愚蠢 :) 但是我已经复制粘贴了数百个解决方案 noee 并尝试了我能想到的一切(我对 VUE 和 JS 完全陌生,所以请善待:))
这是我现在拥有的代码。我可以看到它在 F12 中获取数据,但我无法将数据放入可以在函数外部使用的变量中。
我想对我的数据做一些 reponseDataToSession.user.name 等等,或者循环遍历一些数据,但是如果我在我的 fetch 之外使用 console.log,我会得到空或什么都没有。
请帮助我让我的代码整天都在这个小东西上工作。
我得到的错误是:ReferenceError:reponseDataToSession 未定义
所以这里是代码。
<template>
<div id="app">
<input
v-model="sessionUUID"
@keyup.enter="fetchsessions()"
name="search"
type="text"
/>
<input
@mouseup="fetchsessions()"
name="serchSubmit"
value="SÖK"
type="submit"
/>
<template v-if="viewData">
{{responseDataToSession}}
</template>
</div>
</template>
<script>
import base64 from "base-64";
export default {
name: "App",
data() {
return {
sessionUUID: "",
responseDataToSession: {},
viewData: false,
};
},
methods: {
fetchsessions: function () {
const url = "http://localhost:8080/gethistory";
const method = "POST"
const username = "user";
const password = "bass";
const body = JSON.stringify({"uuid": "' + this.sessionUUID + '","answers": []});
const headers = new Headers();
headers.append("Content-Type", "application/json");
headers.append("Authorization", "Basic " + base64.encode(username + ":" + password));
this.responseDataToSession = fetching();
console.log("1"+this.reponseDataToSession)
this.viewData = true
async function fetching() {
return this.responseDataToSession = await fetch(url, { method, headers, body });
}
}
}
};
</script>
解决方案
你有一个ReferenceError: response is not defined
因为你必须在之前声明你的变量响应。所以你应该写:
async function fetching() {
const response = await fetch(url, { method, headers, body });
return response
}
或者直接(如果您的变量“响应”仅适用于您不需要的功能)
async function fetching() {
return await fetch(url, { method, headers, body });
}
对于responseDataToSession
, 尝试使用responseDataToSession: {}
,
推荐阅读
- javascript - 更新道具反应后如何更新组件
- reactjs - 使用 React Select 为带有 css 模块的子组件设置样式
- c# - 匹配优于 C# 应用程序中的舍入
- git - 如何撤消现有远程存储库中的 git init --bare
- asp.net - ViewBag 读取视图中的字符
- angular - 多个数据和[对象] [对象]
- c# - C# UWP 在 ListView-Binding 中更改图像源
- python - 在使用 standardScaler 和 ols 进行拟合后转换“后退”比例系数
- c# - 如何将反射与非泛型类型一起使用
- java - 在eclipse中添加扩展库