您当前的位置: 首页 > 学无止境 > JS经典实例 网站首页JS经典实例
axios取消请求
发布时间:2020-03-15 19:28:28编辑:雪饮阅读()
<!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.prototype.$axios = axios
var App = {
data() {
return {
file: {},
rate:0,
isShow:false
}
},
template:`<div class='app'>
<input type="file" @change="selfile"/>
<button @click="upload">上传</button>
<button @click="cancel">取消</button>
<div v-show='isShow'>{{rate}}%</div>
</div>`,
methods:{
upload(){
var fd=new FormData;
fd.append('file',this.file);
this.isShow=true;
//获取取消请求资源
var CancelToken = this.$axios.CancelToken;
var source = CancelToken.source();
//将取消请求的资源存储,便于用户取消时调用
this.source=source;
this.$axios.post('upload.php',fd,{
//携带取消请求标识,拥有此标识的请求才可以被取消
cancelToken: source.token,
onUploadProgress:(progressEvent=>{
console.log("上传进度",progressEvent);
var progress=progressEvent.loaded/progressEvent.total*100;
this.$nextTick(function() {
this.rate = Math.ceil(progress);
})
})
});
},
cancel() {
this.source.cancel('请求被取消');
},
selfile(evt){
console.log("file",evt);
this.file=evt.target.files[0];
}
}
};
new Vue({
el: '#app',
template: `<App />`,
components:{App}
});
</script>
</body>
</html>
关键字词:axios,取消请求