如何在Vue.js上下文中处理axios错误 [英] How to handle the axios errors in the context of Vuejs
问题描述
我想在我的API返回任何错误时显示/打印已禁用",并在以200 ok的状态成功返回时显示已启用".
I want to display/print 'Disabled' when ever my API returns any error and display 'Enabled' when it is returning successfully with 200 ok status.
这是我的API返回的内容:
Here's what my API is returning:
因此,我的API当前正在返回错误,因此我要打印/显示已禁用".
So, my API is returning error currently, so i want to print/display 'Disabled'.
这是我的做法:
<template>
<div class="api_data">
<span class="trick_not_ok" v-if="error" >{{error}}</span>
<span class="trick_ok" v-if="noerror" >{{noerror}}</span>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: Api_data,
data () {
return {
error: [],
noerror: []
}
},
created() {
axios.get('...URL...')
.then((response) => {
console.log(response.data)
this.noerror = 'Enabled'
})
.catch((error) => {
if (error) {
console.log(error)
this.error = 'Disabled'
}
})
}
}
</script>
但是我的屏幕上没有打印/显示任何内容,并且我的控制台出现错误,因为获取... URL ... 401(未经授权),当出现以下情况时如何显示已禁用"我的API成功返回后,我的API返回错误并显示已启用".
But nothing is printed/displayed on my screen, and i am getting error in my console as GET ...URL... 401 (UNAUTHORIZED), How do i display 'Disabled' when my API returns error and 'Enabled' when my API is returning successfully.
注意:我也尝试在.catch中尝试使用(error.response.stastus)和if(error.status),但两者均无法正常工作,并且我在控制台中遇到相同的错误.
Note: I have also tried in .catch as if (error.response.stastus) and if (error.status) but both did not work and i am getting the same error in my console.
请有人帮我解决这个问题.
Someone please do help me with this.
推荐答案
此处是我会为您解决麻烦的Codepen解决方案.使用布尔值选择状态,然后使用要显示的消息的字符串.
Here is a codepen solution that I'd use for your trouble. Using boolean for selecting the status and then string for the message you want to display.
new Vue({
el: "#app",
data () {
return {
isError: false,
noerror: false,
message:'loading'
}
},
created() {
axios.get('...URL...')
.then((response) => {
console.log(response.data)
this.noerror = true
this.message = 'enabled'
})
.catch((error) => {
if (error) {
console.log(error)
this.isError = true
this.message = 'disabled'
}
})
},
methods: {
toggle: function(todo){
todo.done = !todo.done
}
}
})
<div id="app">
<div class="api_data">
<span class="trick_not_ok" v-if="isError">{{message}}</span>
<span class="trick_ok" v-if="noerror">{{message}}</span>
</div>
</div>
这篇关于如何在Vue.js上下文中处理axios错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!