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,所以也会收到同源策略的影响。

猜你喜欢

转载自www.cnblogs.com/ghh520/p/12951711.html