Home  >  Q&A  >  body text

Using useRoute in composable Vue3

I have a file store/service.js and I want to use router.

I do this:

import { useRoute } from 'vue-router';
const router = useRoute();
function exceptionHandler(error) {
  if (error.response.status === 401) {
    router.push('/user/login');
  } else if (error.response.status === 404) {
    throw new Error(error.response.data.Message || error.message);
  } else {
    router.push('/error');
  }
}

But I received an undefined error while using the router.

Note: This is not within the setup tag, this is a js external file

P粉937382230P粉937382230290 days ago783

reply all(1)I'll reply

  • P粉982054449

    P粉9820544492023-11-23 10:42:44

    useRoute() can only be used inside settings, so try writing the function as a composable like this

    import { useRoute } from 'vue-router';
    
    export function useExceptionHandler(){
    
    const router = useRoute();
    
    function exceptionHandler(error) {
      if (error.response.status === 401) {
        router.push('/user/login');
      } else if (error.response.status === 404) {
        throw new Error(error.response.data.Message || error.message);
      } else {
        router.push('/error');
      }
    }
        return {
            exceptionHandler,
        }
    }
    

    You can use it on your component like this

    <script setup>
    
    const { exceptionHandler } = useExceptionHandler();
    
    </script>
    

    reply
    0
  • Cancelreply