選單
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue 教程

Vue 首頁 Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue 的原因、方法和設定 Vue 第一個 SFC 頁面 Vue 元件 Vue Props Vue v-for 元件 Vue $emit() Vue fallthru 屬性 Vue 作用域樣式 Vue 本地元件 Vue Slots Vue v-slot Vue 作用域 Slots Vue 動態元件 Vue Teleport Vue HTTP 請求 Vue 模板 Refs Vue 生命週期鉤子 Vue Provide/Inject Vue 路由 Vue 表單輸入 Vue 動畫 Vue v-for 動畫 Vue 構建 Vue Composition API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue 示例

Vue Examples Vue Exercises Vue Quiz Vue Server Vue Certificate

Vue HTTP 請求

HTTP 請求是客戶端和伺服器之間通訊的一部分。

客戶端向伺服器傳送一個HTTP 請求,伺服器處理該請求並返回一個 HTTP 響應。

HTTP

HTTPHyperTextTransferProtocol(超文字傳輸協議)的縮寫。

當我們瀏覽網際網路時,我們的瀏覽器一直在後臺傳送 HTTP 請求。當我們訪問一個網頁時,我們的瀏覽器(客戶端)會發送多個 HTTP 請求,讓伺服器將我們想要的頁面以及所有相關檔案和資料作為 HTTP 響應傳送給我們。

最常見的 HTTP 請求型別是 POSTGETPUTPATCHDELETE。在我們HTTP 請求方法頁面上了解更多關於不同型別的 HTTP 請求。

在我們HTTP 是什麼頁面上了解更多關於 HTTP 的資訊。


‘fetch’ 方法

要在 Vue 中從伺服器獲取資料,我們可以使用 JavaScript 的 fetch() 方法。

在本教程中使用 fetch() 方法時,我們不會指定 HTTP 請求方法,這意味著預設使用的請求方法是 GET

fetch() 方法需要一個 URL 地址作為引數,這樣它才知道從哪裡獲取資料。

這是一個簡單的例子,它使用 fetch() 方法傳送一個 HTTP GET 請求,並以 HTTP 響應接收資料。本例中請求的資料是本地檔案 file.txt 中的文字。

示例

App.vue:

<template>
  <div>
    <button @click="fetchData">Fetch Data</button>
    <p v-if="data">{{ data }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: null,
    };
  },
  methods: {
    fetchData() {
      const response = fetch("file.txt");
      this.data = response;
    }
  }
};
</script>
執行示例 »

在上面的示例中,我們只得到 "[object Promise]" 作為結果,但這並不是我們想要的。

我們得到這個結果是因為 fetch() 是一個基於 Promise 的方法,它返回一個 Promise 物件。因此,fetch() 方法第一次返回的只是一個物件,表示 HTTP 請求已被髮送。這是“pending”(待定)狀態。

fetch() 方法實際獲取到我們想要的資料時,Promise 就會 fulfilled(已完成)。

要等待響應 fulfilled 並獲得我們想要的資料,我們需要在 fetch() 方法前面使用 await 運算子。

const response = await fetch("file.txt");

await 運算子在方法內使用時,該方法需要使用 async 運算子進行宣告。

async fetchData() {
  const response = await fetch("file.txt");
  this.data = response;
}

async 運算子告訴瀏覽器該方法是非同步的,這意味著它會等待某些事情發生,並且瀏覽器在等待方法完成時可以繼續執行其他任務。

現在我們得到的是一個“Response”(響應),而不是一個“Promise”(Promise),這意味著我們離獲取 file.txt 檔案中的實際文字又近了一步。

示例

App.vue:

<template>
  <div>
    <button @click="fetchData">Fetch Data</button>
    <p v-if="data">{{ data }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: null,
    };
  },
  methods: {
    async fetchData() {
      const response = await fetch("file.txt");
      this.data = response;
    }
  }
};
</script>
執行示例 »

要獲取 file.txt 檔案中的文字,我們需要在響應上使用 text() 方法。由於 text() 方法是基於 Promise 的方法,我們需要在它前面使用 await 運算子。

終於!現在我們擁有了使用 fetch() 方法從 file.txt 檔案中獲取文字所需的一切。

示例

App.vue:

<template>
  <div>
    <button @click="fetchData">Fetch Data</button>
    <p v-if="data">{{ data }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: null,
    };
  },
  methods: {
    async fetchData() {
      const response = await fetch("file.txt");
      this.data = await response.text();
    }
  }
};
</script>
執行示例 »

從 JSON 檔案獲取資料

在上一個示例中,我們從 .txt 檔案中獲取了文字。但是資料有很多儲存方式,現在我們將看到如何從 .json 檔案中獲取資訊。

JSON 是一種常見的檔案格式,易於使用,因為它將資料儲存為文字,便於人類閱讀,並且 JSON 格式也得到了程式語言的廣泛支援,因此我們可以,例如,指定要從 .json 檔案中提取什麼資料。

要從 .json 檔案讀取資料,我們只需要對上面的示例進行一個更改,就是獲取一個 .json 檔案,並在響應上使用 json() 方法而不是 text() 方法。

json() 方法讀取 HTTP 請求的響應並返回一個 JavaScript 物件。

我們在這裡使用 <pre> 標籤來顯示 JSON 格式的文字,因為它保留了空格和換行符,使其更易於閱讀。

示例

App.vue:

<template>
  <div>
    <button @click="fetchData">Fetch Data</button>
    <pre v-if="data">{{ data }}</pre>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: null,
    };
  },
  methods: {
    async fetchData() {
      const response = await fetch("bigLandMammals.json");
      this.data = await response.json();
    }
  }
};
</script>
執行示例 »

由於 json() 方法的結果是一個 JavaScript 物件,我們可以修改上面的示例來顯示 bigLandMammals.json 檔案中的一個隨機動物。

示例

App.vue:

<template>
  <p>Try clicking the button more than once to see new animals picked randomly.</p>
  <button @click="fetchData">Fetch Data</button>
  <div v-if="randomMammal">
    <h2>{{ randomMammal.name }}</h2>
    <p>Max weight: {{ randomMammal.maxWeight }} kg</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      randomMammal: null
    };
  },
  methods: {
    async fetchData() {
      const response = await fetch("bigLandMammals.json");
      const data = await response.json();
      const randIndex = Math.floor(Math.random()*data.results.length);
      this.randomMammal = data.results[randIndex];
    }
  }
};
</script>
執行示例 »

來自 API 的資料

API 是 Application Programming Interface(應用程式程式設計介面)的縮寫。您可以在此處瞭解更多關於 API 的資訊。

我們可以連線並使用許多有趣的免費 API,以獲取天氣資料、股票交易所資料等。

當我們使用 HTTP 請求呼叫 API 時,我們收到的響應可以包含各種資料,但通常以 JSON 格式包含資料。

示例

可以單擊一個按鈕從 random-data-api.com API 獲取一個隨機使用者。

App.vue:

<template>
  <h1>Example</h1>
  <p>Click the button to fetch data with an HTTP request.</p>
  <p>Each click generates an object with a random user from <a href="https://random-data-api.com/" target="_blank">https://random-data-api.com/</a>.</p>
  <p>The robot avatars are lovingly delivered by <a href="http://Robohash.org" target="_blank">RoboHash</a>.</p>
  <button @click="fetchData">Fetch data</button>
  <pre v-if="data">{{ data }}</pre>
</template>

<script>
  export default {
    data() {
      return {
        data: null,
      };
    },
    methods: {
      async fetchData() {      
        const response = await fetch("https://random-data-api.com/api/v2/users"); 
        this.data = await response.json();
      }   
    }
  };
</script>
執行示例 »

我們可以稍微修改之前的示例,以便以更友好的方式包含隨機使用者。

示例

當按鈕被點選時,我們會在 <pre> 標籤中顯示隨機使用者的姓名、職位和圖片。

App.vue:

<template>
  <h1>Example</h1>
  <p>Click the button to fetch data with an HTTP request.</p>
  <p>Each click generates an object with a random user from <a href="https://random-data-api.com/" target="_blank">https://random-data-api.com/</a>.</p>
  <p>The robot avatars are lovingly delivered by <a href="http://Robohash.org" target="_blank">RoboHash</a>.</p>
  <button @click="fetchData">Fetch data</button>
  <div v-if="data" id="dataDiv">
    <img :src="data.avatar" alt="avatar">
    <pre>{{ data.first_name + " " + data.last_name }}</pre>
    <p>"{{ data.employment.title }}"</p>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        data: null,
      };
    },
    methods: {
      async fetchData() {      
        const response = await fetch("https://random-data-api.com/api/v2/users"); 
        this.data = await response.json();
      },    
    }
  };
</script>

<style>
#dataDiv {
  width: 240px;
  background-color: aquamarine;
  border: solid black 1px;
  margin-top: 10px;
  padding: 10px;
}
#dataDiv > img {
  width: 100%;
}
pre {
  font-size: larger;
  font-weight: bold;
}
</style>
執行示例 »

使用 'axios' 庫在 Vue 中進行 HTTP 請求

'axios' JavaScript 庫也允許我們進行 HTTP 請求。

要建立示例並在您自己的機器上執行它,您需要先在專案資料夾中使用終端安裝 'axios' 庫,如下所示:

npm install axios

這是我們在 Vue 中使用 'axios' 庫獲取隨機使用者的方法。

示例

與之前的示例相比,只進行了少量更改,以便使用 'axios' 庫而不是其他方法進行 HTTP 請求。

App.vue:

<template>
  <h1>Example</h1>
  <p>Click the button to fetch data with an HTTP request.</p>
  <p>Each click generates an object with a random user from <a href="https://random-data-api.com/" target="_blank">https://random-data-api.com/</a>.</p>
  <p>The robot avatars are lovingly delivered by <a href="http://Robohash.org" target="_blank">RoboHash</a>.</p>
  <button @click="fetchData">Fetch data</button>
  <div v-if="data" id="dataDiv">
    <img :src="data.data.avatar" alt="avatar">
    <pre>{{ data.data.first_name + " " + data.data.last_name }}</pre>
    <p>"{{ data.data.employment.title }}"</p>
  </div>
</template>

<script>
  import axios from 'axios'

  export default {
    data() {
      return {
        data: null,
      };
    },
    methods: {
      async fetchData() {      
        this.data = await axios.get("https://random-data-api.com/api/v2/users");
      }
    }
  };
</script>

<style>
#dataDiv {
  width: 240px;
  background-color: aquamarine;
  border: solid black 1px;
  margin-top: 10px;
  padding: 10px;
}
#dataDiv > img {
  width: 100%;
}
pre {
  font-size: larger;
  font-weight: bold;
}
</style>
執行示例 »


×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援