您当前的位置: 首页 > 学无止境 > JS经典实例 网站首页JS经典实例
vue的axios(其实感觉和原生js的promise没有多大区别)
发布时间:2020-03-08 18:22:41编辑:雪饮阅读()
安装
npm install axios –save
使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript" src="./node_modules/axios/dist/axios.js"></script>
<script type="text/javascript">
//将全局绑定给vue
Vue.prototype.$axios = axios
var App = {
template:`<div class='app'>
<button @click="send">发请求</button>
<button @click="sendAll">请求队列</button>
</div>`,
methods:{
//普通请求,api支持promise接口特性
send(){
this.$axios.get('1.php').then(res=>{
console.log("成功",res);
}).catch(res=>{
console.log("失败",res);
})
},
//队列请求,全部成功才算成功,一个失败就算失败
sendAll(){
this.$axios.defaults.baseURL='http://127.0.0.1/';
//为空时是index
var q1=this.$axios.get("");
var q2=this.$axios.post('add.php','a=1');
this.$axios.all([q1,q2]).then(this.$axios.spread((res1,res2)=>{
//全部成功了
console.log("res1",res1);
console.log("res2",res2);
this.res1=res1.data;
this.res2=res2.data;
})).catch(err=>{
console.log("其一失败",err);
});
}
}
};
new Vue({
el: '#app',
template: `<App />`,
components:{App}
});
</script>
</body>
</html>
关键字词:axios,请求,队列,promise