Vue在組件中使用axios獲取數據


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>

效果:

1552202922168

使用的時候,因為本質上來說,我們還是原來的axios,所以也會收到同源策略的影響。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM