Home > Net >  useRoute in composible vue3
useRoute in composible vue3

Time:08-13

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

I make 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 received a error undefined in router use.

note: this is not inside setup tag, this is a js external file

CodePudding user response:

This should be defined inside a setup hook or script setup in a component that belongs to instance using vue router. So in your case it could be defined in the setup and passed as argument to the composable function :

function exceptionHandler(error, router) {
  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');
  }
}

CodePudding user response:

Yeah, this is not quite possible, you can only use useRoute in setup, because that's a hook. What you can do, however, is to import the router from its file into your script and use it.

CodePudding user response:

useRoute() can only be used inside setup so try to write your 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,
    }
}

and you can use it like this on your component

<script setup>

const { exceptionHandler } = useExceptionHandler();

</script>
  • Related