前言:
Vue官方推荐使用axios来进行异步访问。
axios文档参考:axios中文文档
开始搭建:
1.引入axios
(1)打开终端
win+R
(2)切换到项目路径:
g:
cd Webapp\Vue\vue_05
(3)引入axios:
cnpm install axios --save
2.全局配置axios
(1)src目录下创建util\HttpRequestUtil.js
import axios from 'axios' /**
* Get请求
*/
export function get(url, callback){
console.log('测试get请求')
axios.get(url)
.then(function (response) {
console.log(response)
callback(response.data,true)
})
.catch(function (error) {
console.log(error)
callback(null,false)
})
} export default {
get
}
(2)组件中调用App.vue
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view/>
</div>
</template> <script>
import httpUtil from '@/util/HttpRequestUtil'
export default {
name: 'App',
methods: {
test() {
var url = 'https://www.baidu.com/'
httpUtil.get(url,function(data,status){
console.log(data)
console.log(status)
})
}
},
created(){
this.test()
}
}
</script> <style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>