axios調用接口
1. 按照axios
npm install --save-dev axios
2.在main.js 引入axios,
設置全局屬性$http 指向axios
main.js
import axios from 'axios'
Vue.prototype.$http = axios
3.data中定義一個變量
return {
testData: []
}
}
methods中定義調用API數據的方法
methods: {
getData () {
// this是指向當前vue實例,千萬不能丟掉,不然會報方法或對象undefined
// 調用的接口是豆瓣公開的,可以直接測試調用
this.$http.get('https://api.douban.com/v2/book/1220562').then(response => {
this.testData = response.data
}).catch(error => {
console.log(error)
})
}
}
created 鈎子用來在一個實例被創建之后執行該方法
created () {
this.getData()
}
4.webpack配置代理跨域
config文件夾下的index.js中的proxyTable屬性就是提供本地代理配置項,可根據Vue-cli使用插件介紹配置如下即可
代碼:
proxyTable: {
'/v2': {
target: 'https://api.douban.com',
changeOrigin: true,
pathRewrite: {
// /v2將代表target/v2
'^/v2': '/v2'
}
}
}
5. 將url:'https://api.douban.com/v2/book/1220562'修改為:'/v2/book/1220562',修改完成
6.
組件數據展示
將testData綁到template里,發現組件已經調用數據成功了
完整代碼:
<template>
<span>{{ testData }}</span>
</template>
<script>
export default{
data () {
return {
testData: []
}
},
created () {
this.getData()
},
methods: {
getData () {
// this是指向當前vue實例,千萬不能丟掉,不然會報方法或對象undefined
// 調用的接口是豆瓣公開的,可以直接測試調用
this.$http.get('/v2/book/1220562').then(response => {
this.testData = response.data
}).catch(error => {
console.log(error)
})
}
}
}
</script><style type="text/css"></style>
轉載:
https://www.2cto.com/kf/201801/714145.html
