Vue cli之在元件中使用axios
阿新 • • 發佈:2021-10-02
預設情況下,我們的專案中並沒有對axios包的支援,所以我們需要下載安裝。
在專案根目錄中使用 npm安裝包:
npm install axios
接著在main.js檔案中,匯入axios並把axios物件 掛載到vue屬性中多為一個子物件,這樣我們才能在元件中使用。
main.js補充程式碼:
import axios from "axios"; // 初始化axios物件 Vue.prototype.$http = axios.create(); Vue.config.productionTip = false
建立Forecast元件:
<template> <div> <input type="text" v-model="city"> <button @click="get_weather">獲取天氣</button> <table v-if="weather_list.length>1"> <tr> <th>日期</th> <th>天氣</th> <th>溫度</th> <th>風向</th> </tr> <tr v-for="weather in weather_list"> <td>{{weather.date}}</td> <td>{{weather.type}}</td> <td>{{weather.low}}~{{weather.high}}</td> <td>{{weather.fengxiang}}{{weather.fengli|format}}</td> </tr> </table> </div> </template> <script> export default { name: "Index", data(){ return { city: "北京", weather_list:[], } }, filters:{ format(content){ return content.replaceAll("<![CDATA[","").replaceAll("]]>",""); } }, methods:{ get_weather(){ // 傳送http請求獲取天氣 this.$http.get("http://wthrcdn.etouch.cn/weather_mini",{ params:{ city: this.city, } }).then(response=>{ console.log(response.data.data.forecast); this.weather_list = response.data.data.forecast; }).catch(error=>{ console.log(error); }) } } } </script> <style scoped> table{ width: 800px; border-collapse: collapse; } td,th{ border: 1px solid red; } </style>
home元件更新為:
效果:
使用的時候,因為本質上來說,我們還是原來的axios,所以也會收到同源策略的影響。