一、背景
在一个vue的demo项目中使用axios发起请求
ps:本文章只是一个入门的小栗子,不复杂,可以帮助初学者有个大概的了解,不涉及axios封装,之类的框架层面东西。
二、先准备一个前端vue小工程
工程搭建方法看这个文章
https://blog.youkuaiyun.com/giiiig/article/details/116757737
三、在工程中调用axios
1、在src.main.js中引入axios
import axios from 'axios'
Vue.prototype.$http = axios
2、在组件中(src.components.HelloWorld.vue)调用axios,发起请求
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: null
}
}, mounted () {
var vm = this
this.$http
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(function (response) {
console.log('debug------',response.data)
vm.msg = response.data.bpi
})
}
}
</script>
3、使用接口返回的数据,还是src.components.HelloWorld.vue文件
<template>
<div class="hello">
<h1>{{ msg }}</h1>
</div>
</template>
源码我上传到这里了 https://github.com/gogocomeon/vue-axios-demo
四、效果