vue.js2.0後版本推荐使用axios
来完成ajax
请求
为Promise-based HTTP client
非同步
,可於then
後进行操作、catch
错误处理,有finlly机制(同步
)。
// npm
$ npm install axios
// yarn
$ yarn add axios
// CDN
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
引入於main.js
import axios from 'axios'
Vue.prototype.$axios = axios;
依照官方案例呼叫於mounted。
mounted() {
this.$axios
.get("https://api.coindesk.com/v1/bpi/currentprice.json")
// 成功
.then((response) => console.log(response))
// 错误处理
.catch((error) => console.log(error))
// 必执行,类似finally
.then(console.log('must run'))
},
回传为JSON格式,可透过.
取数据,也可进行遍历
、过滤
...等操作。
以下范例调整为function形式(进行多处理)
.then(function (response) {
console.log(response.data.bpi);
console.log(response.data.bpi.USD);
})
.get("https://my.api.url", {
params: {
id: '0001',
},
})
基础用法与GET相同。
this.$axios
.post("https://my.api.url")
// 成功
.then((response) => console.log(response))
// 错误处理
.catch((error) => console.log(error))
// 必执行,类似finally
.then(console.log('must run'))
// 直接进行宣告
.post("https://my.api.url", {
id: "0001",
name: "su",
})
// 透过变数
.post("https://my.api.url", this.todo)
透过all
、spread
实现
定义方法
methods: {
doGetOne: function () {
return this.$axios.get(
"https://api.coindesk.com/v1/bpi/currentprice.json"
);
},
doGetTwo: function () {
return this.$axios.get(
"https://api.coindesk.com/v1/bpi/currentprice.json"
);
},
}
mounted
mounted() {
this.$axios.all([this.doGetOne(), this.doGetTwo()]).then(
this.$axios.spread(function (acct, perms) {
// API皆执行完成
console.table(acct);
console.table(perms.data);
})
);
},
log1 :doGetOne return,完整回传
log2 :function doGetTwo,透过data取数据
有错误请不吝指教!
参考资料
https://vuejs.org/v2/guide
https://ithelp.ithome.com.tw/articles/10194612
https://www.runoob.com/vue2/vuejs-ajax-axios.html
https://tools.wingzero.tw/article/sn/138
https://www.jb51.net/article/199256.htm
<<: ESP32_DAY10 硬体届的Hello World!
WordPress 全球市占率突破了约 42%,依赖於来自全球努力的志工,但由於中文市场上对推广 ...
亚萨尔斯火焰烤饼,火焰烤饼是道很适合跟好友家人一起分享,很适合在节日庆典上搭配红酒的美食 来自法国亚...
阿罗哈~ 现在心情之放松 原因是游戏专题告一段落拉 排名会在下周公布 保佑我们可以在中间以上的名次就...
完赛罗 baby 这是我第一次参加铁人赛,这一个月下来,不仅算是给予暑假两个月的我一个复习的机会、加...
心得感想 经历了二十周,五个月的培训,从一个连回圈都不太懂的外行人,到可以自己写出一个App(虽...