8. 在組件中使用axios獲取數據
默認情況下,我們的項目中並沒有對axios包的支持,所以我們需要下載安裝。
在項目根目錄中使用 npm安裝包
npm install axios
接着在main.js文件中,導入axios並把axios對象 掛載到vue屬性中多為一個子對象,這樣我們才能在組件中使用。
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App' // 這里表示從別的目錄下導入 單文件組件
import axios from 'axios'; // 從node_modules目錄中導入包
Vue.config.productionTip = false
Vue.prototype.$axios = axios; // 把對象掛載vue中
/* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
template: '<App/>'
});
8.1 在組建中使用axios獲取數據
<script>
export default{
。。。
methods:{
get_data:function(){
// 使用axios請求數據
this.$axios.get("http://wthrcdn.etouch.cn/weather_mini?city=深圳").then((response)=>{
console.log(response);
}).catch(error=>{
console.log(error);
})
}
}
}
</script>
效果:
使用的時候,因為本質上來說,我們還是原來的axios,所以也會收到同源策略的影響。