3.vue引入axios全局配置

前言:

Vue官方推荐使用axios来进行异步访问。

axios文档参考:axios中文文档

开始搭建:

1.引入axios

(1)打开终端

win+R

(2)切换到项目路径:

g:

cd WebappVuevue_05

(3)引入axios:

cnpm install axios --save

2.全局配置axios

(1)src目录下创建utilHttpRequestUtil.js

 1 import axios from 'axios'
 2 
 3 /**
 4  * Get请求
 5  */
 6 export function get(url, callback){
 7     console.log('测试get请求')
 8     axios.get(url)
 9     .then(function (response) {
10         console.log(response)
11         callback(response.data,true)
12     })
13     .catch(function (error) {
14         console.log(error)
15         callback(null,false)
16     })
17 }
18 
19 
20 export default {
21     get
22 }

(2)组件中调用App.vue

 1 <template>
 2   <div id="app">
 3     <img src="./assets/logo.png">
 4     <router-view/>
 5   </div>
 6 </template>
 7 
 8 <script>
 9 import httpUtil from '@/util/HttpRequestUtil'
10 export default {
11   name: 'App',
12   methods: {
13     test() {
14       var url = 'https://www.baidu.com/'
15       httpUtil.get(url,function(data,status){
16           console.log(data)
17           console.log(status)
18       })
19     }
20   },
21   created(){
22     this.test()
23   }
24 }
25 </script>
26 
27 <style>
28 #app {
29   font-family: 'Avenir', Helvetica, Arial, sans-serif;
30   -webkit-font-smoothing: antialiased;
31   -moz-osx-font-smoothing: grayscale;
32   text-align: center;
33   color: #2c3e50;
34   margin-top: 60px;
35 }
36 </style>
原文地址:https://www.cnblogs.com/TimerHotel/p/vue_03.html