天天看點

hualinux 進階 vue 4.0:使用axios與後端互動

目錄

​​一、axios介紹​​

​​二、aiios安裝​​

​​2.1 vue-axios安裝介紹​​

​​CommonJS:​​

​​2.2 使用webStorm安裝​​

​​三、例子​​

前面說所說的vue及相關元件都沒有與後端互動。

因為顯示裝置的多樣化,現在基本上都是使用前後端分離,後端基本上都是使用api方式,基本上是以restful api為主。

是以這篇開始講使用axios與後端api互動。可以先看一下vue.js官方的《​​使用 axios 通路 API​​​》及 “axios中文文檔”中的​​vue-axios​​

一、axios介紹

有很多時候你在建構應用時需要通路一個 API 并展示其資料。做這件事的方法有好幾種,而使用基于 promise 的 HTTP 用戶端 ​​axios​​ 則是其中非常流行的一種。

​​Fetch API​​ 是一個用于此類請求的強大的原生 API。你可能聽說過 Fetch API 其中的一個好處,就是你不需要在使用它的時候額外加載一個外部資源。确實如此!但是……目前它還沒有被浏覽器完全支援,是以你仍然需要一個 polyfill。使用這個 API 還有很多别的注意事項,這也是為什麼大家現階段還是更喜歡 axios 多一些。當然這個事情在未來可能會發生改變。

二、aiios安裝

2.1 vue-axios安裝介紹

根據​​axios中文文檔​​​關于​​vue-axios安裝​​,隻要在vue項目根目錄下執行

CommonJS:

npm install --save axios vue-axios      

将下面代碼加入入口檔案:

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)      

如果是使用腳本的話:按照這個順序分别引入這三個檔案: ​

​vue​

​​, ​

​axios​

​​ and ​

​vue-axios​

該包裝器将axios綁定到Vue,如果您使用的是單個檔案元件,則可以将其綁定。

Vue.axios.get(api).then((response) => {
  console.log(response.data)
})

this.axios.get(api).then((response) => {
  console.log(response.data)
})

this.$http.get(api).then((response) => {
  console.log(response.data)
})      

2.2 使用webStorm安裝

如果是webStorm可以在先點項目,再點最下方的終端Terminal中執行上面的安裝指令即可,如下圖所示:

hualinux 進階 vue 4.0:使用axios與後端互動

安裝完成後,如下圖所示:

hualinux 進階 vue 4.0:使用axios與後端互動

三、例子

​​官網使用 axios 通路 API​​​例子,我在《hualinux 進階 vue 3.1:vue cli手工建立Vue router》例子的基礎上,直接修改。直接修改src/views/About.vue進行通路,代碼如下:

<template>
  <div class="about">
    <div id="app">
      {{ info }}
    </div>
  </div>
</template>

<script>

import axios from "axios";

export default {
  name:'About',
  data(){
    return{
      info: null,
    }
  },
  mounted () {
    axios
        .get('https://api.coindesk.com/v1/bpi/currentprice.json')
        .then(response => (this.info = response))
  }
}
</script>      

運作并打開網頁,點about

hualinux 進階 vue 4.0:使用axios與後端互動

繼續閱讀