簡體   English   中英

VueUse如何在useFetch的onFetchError中調用useRouter?

[英]How to call useRouter inside useFetch's onFetchError by VueUse?

我需要使用 createFetch() 從 VueUse 創建可組合的自定義提取,我想檢查請求是否返回 401 狀態,我希望將路由重定向到登錄路由。

export const useApiFetch = createFetch({
  baseUrl: import.meta.env.VITE_API_BASE_URL,
  options: {
    beforeFetch({ options }) {
      const { user } = useSessionStore()
      if (user)
        options.headers.Authorization = `Basic ${user.user_id}:${user.password}`
      return { options }
    },
    onFetchError(response) {
      const route = useRoute()
      const router = useRouter()
      if (route.name !== 'login' && response.status === 401)
        return router.push('/login')
    }
  }
})

但是每次遇到錯誤時,useRoute 和 useRouter 都是未定義的,是的。我檢查過它是否在設置中運行

<script setup>
const submit = async () => {
  const { error, data } = await useApiFetch('/login').post(form)
}
</script>

我錯過了什么或者有更好的方法嗎? 謝謝

Vue 可組合項主要預期在設置塊中調用。 其他用法取決於它們的實現,需要確認。 主要限制是可組合項鏈接到特定組件實例,在這種情況下, useRouter使用provide / inject通過組件層次結構獲取路由器實例; 這通常可以在不檢查實際實現的情況下推斷出來。

可以直接導入路由器實例而不是使用useRouter ,但這可能會導致模塊循環依賴,並且這可能不適用於其他可組合項。

createFetch並非為此用途而設計,需要使用自定義可組合項進行包裝,以確保及時調用其他可組合項:

let useApiFetchFn;

const useApiFetch = (...args) => {
  if (!useApiFetchFn) {
    const sessionStore = useSessionStore()
    const route = useRoute()
    const router = useRouter()

    useApiFetchFn = createFetch(...)
  }

  return useApiFetchFn(...args);
}

將結果緩存到useApiFetchFn是否正確取決於實現,在這種情況下是可以接受的。 在這一點上,直接使用useFetchcreateFetch那樣組合選項可能更直接,它的大部分代碼專用於 TS 支持和可變參數 arguments,在這種情況下可能不需要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM