【问题标题】:How to stop code execution after routing to error page from vuex?从vuex路由到错误页面后如何停止代码执行?
【发布时间】:2020-09-12 13:18:18
【问题描述】:

我有一个用 VueJs 和 Vuex 编写的购物车页面。我有一个 api 文件,它充当 axios 的包装器。

在我的 vuex 操作中,我调用 API,如果成功,我将数据提交到我的变异中。

async await mounted () {
   const result = this.getStatus()
   if (result === "locked") {
      this.$router.push({name: "LockedPage"}
   }
   else if (result === "expired") {
      this.$router.push({name: "SessionExpiredPage"}
   }

   doSomething(result)
},
methods: {
  function doSomething(res) {
    // does something with result
  }
}

这里的 getStatus 函数来自我的 vuex 操作。

     const {authid, authpwd} = router.history.current.params
     if (!authid || !authpwd) {
       router.push({name: "SomethingWrong"})
       return
     }
     const res = await api.getStatus 
     commit("SET_STATUS", res.status)
     if (res.otherLogic) {
       //commit or trigger other actions
     }

     return status
   }

处理此类 API 错误的理想方法是什么?如果您看一下,您会发现我正在外部组件的挂载钩子内部以及 vuex 操作本身内部进行路由。这个状态函数的所有路由都应该发生在 vuex 操作中吗?

我认为它当前是如何设置的,当SomethingWrong page 被路由时。它仍然会将执行返回到mounted 函数。所以从技术上讲,doSomething 函数仍然可以被调用,但我猜想使用未定义的值。这似乎有点糟糕。在我们将用户路由到错误页面后,有没有办法停止代码执行?路由页面后抛出错误会更好吗?

我应该使用Vue.config.errorHandler = function (err, vm, info) 来捕获我从 vuex 操作中抛出的这些自定义路由错误吗?

【问题讨论】:

    标签: javascript vue.js axios vuex


    【解决方案1】:

    对于像过期会话这样的一般错误,我建议使用拦截器在 axios 级别处理它。 https://github.com/axios/axios#interceptors

    可以定义拦截器,例如。在插件中。添加 Nuxt 插件作为示例(没有 Nuxt 的 Vue 将使用稍微不同的插件定义,但它仍然应该是有用的灵感)(也可以访问窗口,因为 sn-p 来自 SPA 应用程序 - 没有服务器端渲染)

    export default ({ $axios, redirect }) => {
      $axios.onError((error) => {
        const code = parseInt(error.response && error.response.status)
        if (code === 401) {
          // don't use route path, because error is happending before transition is completed
          if (!window.localStorage.getItem('auth.redirect')) {
            window.localStorage.setItem('auth.redirect', window.location.pathname)
          }
          redirect('/login-page')
        }
      })
    }
    

    【讨论】:

    • 当您使用拦截器处理路由时,您是否在调用 axios 时遇到错误?你在做类似 `axios.loginUser().catch(error =>{ // 这在重定向到登录页面后调用})
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2014-01-03
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多