Using useRoute in composable Vue3
P粉937382230
P粉937382230 2023-11-22 23:48:09
0
1
825

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粉937382230
P粉937382230

reply all(1)
P粉982054449

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>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template