如何在Nuxt 2中通过代码重定向至错误页面?
解决Nuxt 2 Vuex Action中触发错误页面的问题
在Nuxt 2里,$error是页面组件的专属方法,Vuex Action的上下文里默认没法直接通过this访问到它,你可以用以下两种方式实现需求:
方案一:在页面fetch中捕获错误并触发错误页面
这种方式更灵活,适合需要在页面层自定义错误处理逻辑的场景:
- 修改Vuex Action,把错误向上抛出:
async fetchVotes ({ commit }) { try { const response = await this.$secured.get('exampleapi.com/votes') const merged = jsonApiMerge(response.data.included, response.data.data) commit(SET_VOTES_LIST, merged) } catch (err) { // 抛出错误,交给调用该action的页面fetch处理 throw err } }
- 在页面的
fetch方法中捕获错误,调用$error:
async fetch() { try { await this.fetchVotes() // 调用映射后的Vuex action } catch (err) { // 处理Axios错误结构,兼容网络错误等无response的情况 const statusCode = err.response?.status || 500 const message = err.message || '请求失败,请稍后重试' this.$error({ statusCode, message }) } }
方案二:直接在Vuex Action中通过Nuxt实例触发错误页面
如果所有调用该action的页面都需要统一的错误处理,可以直接在Action中通过Nuxt实例触发错误页面:
修改Action的catch代码块:
catch (err) { // 通过store实例的$nuxt属性访问Nuxt app实例 this.$nuxt.error({ statusCode: err.response?.status || 500, message: err.message || '获取投票数据失败' }) }
注意:Axios错误需要区分情况,当请求未到达服务器时(如网络错误),err.response会不存在,所以要给statusCode设置默认值。
内容的提问来源于stack exchange,提问作者zcserei
相关产品推荐
相关产品推荐

