谈谈Vue.js——vue-resource全攻略

2020-06-16 06:04:52易采站长站整理

</div>
</div>
</template>

2.将loading组件作为另外一个Vue实例的子组件


var help = new Vue({
el: '#help',
data: {
showLoading: false
},
components: {
'loading': {
template: '#loading-template',
}
}
})

3.将该Vue实例挂载到某个HTML元素


<div id="help">
<loading v-show="showLoading"></loading>
</div>

4.添加inteceptor


Vue.http.interceptors.push((request, next) => {
loading.show = true
next((response) => {
loading.show = false
return response
});
});

示例2

当用户在画面上停留时间太久时,画面数据可能已经不是最新的了,这时如果用户删除或修改某一条数据,如果这条数据已经被其他用户删除了,服务器会反馈一个404的错误,但由于我们的put和delete请求没有处理errorCallback,所以用户是不知道他的操作是成功还是失败了。

你问我为什么不在每个请求里面处理errorCallback,这是因为我比较懒。这个问题,同样也可以通过inteceptor解决。

1. 继续沿用上面的loading组件,在#help元素下加一个对话框


<div id="help">
<loading v-show="showLoading" ></loading>
<modal-dialog :show="showDialog">
<header class="dialog-header" slot="header">
<h1 class="dialog-title">Server Error</h1>
</header>
<div class="dialog-body" slot="body">
<p class="error">Oops,server has got some errors, error code: {{errorCode}}.</p>
</div>
</modal-dialog>
</div>

2.给help实例的data选项添加两个属性


var help = new Vue({
el: '#help',
data: {
showLoading: false,
showDialog: false,
errorCode: ''
},
components: {
'loading': {
template: '#loading-template',
}
}
})

3.修改inteceptor


Vue.http.interceptors.push((request, next) => {
help.showLoading = true
next((response) => {
if(!response.ok){
help.errorCode = response.status
help.showDialog = true
}
help.showLoading = false
return response
});
});