hi, thanks a helpful solution, but, way a your import { router } from '~/main' export?
Access to router.currentRoute... outside of the component in VUEJS
Hello, I don't have a lot of experience in VUEJS and in JS itself, so I probably got stuck on a seemingly trivial topic.
In a word of explanation, the project is a SPA application that communicates with the backend via REST API and is based on VITESSE (boilerplate VUE3 + Typescript + Pinia + composition API ....)
Since the application will be quite complex, I decided to create an abstract layer for communication over HTTP.
In connection with the above, I created a folder / src / api and in it another files with methods divided into groups that perform specific queries via axios (as below)
import type { AxiosInstance, AxiosRequestConfig } from 'axios'
import axios from 'axios'
import { router } from '~/main'
const axiosInstance: AxiosInstance = axios.create({
baseUrl: import.meta.env.API_URL,
headers: {
'Content-type': 'application/json',
'Authorization': 'Bearer ' + 'TOKENXXXXXXXXXXXXX',
'Language': router.currentRoute.value.params.lang,
},
})
async function axiosCall<T>(config: AxiosRequestConfig) {
try {
const { data } = await axiosInstance.request<T>(config)
return [null, data]
}
catch (error) {
return [error]
}
}
export async function sendMessage(formData) {
return axiosCall<void>({ method: 'post', url: '/send-message', data: formData })
}
DESCRIPTION OF THE PROBLEM
In "headers" I would like to put the currently selected language by the user (from the URL) into the backend:
'Language': router.currentRoute.value.params.lang,
the only problem is that the router is probably "uninitialized" at this point.
Even though I'm on the url / en / contact, router.fullPath shows "/" and router.currentRoute.value.params is an empty object
however, if I do something like this in the above file:
async function getLang () {
await router.isReady ()
console.log ('routerLang:', router.currentRoute.value.params.lang)
}
getLang ()
then, of course, "routerLang: en" appears on the console
Of course, the workaround is to extract the language from the "window.location.href" available at this stage, but this is for sure bad solution
How should I deal with such problems?
Regards and thank you in advance
Please or to participate in this conversation.