Vue调用REST API获取数据后无法在函数外访问变量求助
Fixing Your Vue Fetch Data Issue: Accessing Response Outside Fetch
Hey there! Let's work through this together—you've put in a whole day on this, so let's break down the problems and fix them step by step. As a Vue/JS newbie, these async data headaches are super common, so don't beat yourself up over it!
Key Issues in Your Code
- Typos: You wrote
this.reponseDataToSession(missing an 's' in 'response') in yourconsole.log—that's the direct cause of yourReferenceError. Always double-check variable names! - Async/Await Misuse: Your
fetchsessionsmethod wasn't marked as async, and the innerfetchingfunction had athiscontext problem (regular functions don't automatically bind to the Vue instance). - Fetch Returns a Response Object: You were assigning the raw
fetchresponse directly to your data property, but you need to parse it to JSON first to get the actual server data. - Broken String Interpolation: Your
bodyused messy, incorrect string concatenation—template literals are cleaner and more reliable here.
Fixed Code
<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: { // Mark method as async to use await inside async fetchsessions() { const url = "http://localhost:8080/gethistory"; const method = "POST"; const username = "user"; const password = "bass"; // Clean up body with direct property assignment 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)); try { // Wait for fetch to complete, then parse response to JSON const response = await fetch(url, { method, headers, body }); this.responseDataToSession = await response.json(); console.log("Fetched data:", this.responseDataToSession); this.viewData = true; } catch (error) { // Add error handling to catch network/server issues console.error("Error fetching data:", error); this.viewData = false; } } } }; </script>
What Changed & Why
- Marked
fetchsessionsasasync: This lets us useawaitto pause execution until the fetch finishes, so we don't try to access data before it's loaded. - Removed the inner
fetchingfunction: It was causingthiscontext confusion—handling the fetch directly in the method keepsthisbound to the Vue instance. - Parsed response with
.json(): The raw fetch response is just an HTTP wrapper;.json()extracts the actual data sent by your server. - Fixed the
bodyobject: Usingthis.sessionUUIDdirectly avoids broken string concatenation, ensuring your server gets the correct UUID. - Added
try/catch: This helps you debug failed requests (like network errors) instead of them failing silently. - Fixed the typo: Now
console.loguses the correctly spelledthis.responseDataToSession.
Accessing Your Data
Now you can access nested properties like this.responseDataToSession.user.name anywhere in your component. In the template, use optional chaining (?.) to avoid errors if data isn't loaded yet:
<template v-if="viewData"> <p>User Name: {{ responseDataToSession.user?.name }}</p> </template>
Optional chaining safely handles cases where user might not exist yet (like before the fetch completes).
内容的提问来源于stack exchange,提问作者andersson123
相关产品推荐
相关产品推荐

