Entonces, estoy tratando de redirigir al usuario a una ruta diferente si la llamada api devuelve el estado 422. Pero recibo un error
TypeError: Cannot read properties of undefined (reading '$router')mis rutas.js:
{ path: '/dashboard', component: Dashboard, name: 'Dashboard', beforeEnter: (to, form, next) =>{ axios.get('/api/authenticated') .then(()=>{ next(); }).catch(()=>{ return next({ name: 'Login'}) }) }, children: [ { path: 'documentCollections', component: DocumentCollection, name: 'DocumentCollections' }, { path: 'document', component: Document, name: 'Document' }, { path: 'createDocument', component: CreateDocument, name: 'CreateDocument' }, { path: 'suppliers', component: Suppliers, name: 'Suppliers' }, { path: 'settings', component: Settings, name: 'Settings' }, ] }También tengo componentes de inicio de sesión/registro y cuando uso
this.$router.push({ name: "DocumentCollections"});Redirige al usuario sin ningún error. El problema es cuando estoy en el componente secundario del componente del tablero.
en el componente documentCollections tengo un método:
loadCollections(){ axios.get('/api/documentCollections') .then((response) => { this.Collections = response.data.data this.disableButtons(response.data.data); }) .catch(function (error){ if(error.response.status === 422){ //here is where the error happens this.$router.push({ name: "Settings"}); } }); },Eso carga las colecciones, pero si el usuario tiene algún conjunto de datos, el estado de retorno de la API nula es 422. y quiero que sea redirigido al componente Configuración. (tanto documentCollection como Settings son componentes secundarios de Dashboard)
¿Por qué this.$router.push no funciona aquí pero funciona en el componente de inicio de sesión/registro?
Llamar a this dentro de una función de devolución de llamada crea un nuevo enlace a this objeto en lugar del objeto Vue en una expresión de función regular.
Puede usar la sintaxis de flecha para definir la función, por this no se sobrescribirá.
.catch((error) => { if(error.response.status === 422){ this.$router.push({name: "Settings"}); } }) Defina otra instancia de this antes de la llamada axios y utilícela después de recibir la respuesta.
let self = this ... self.$router.push({name: "Settings"})con tu codigo
loadCollections(){ let self = this; axios.get('/api/documentCollections') .then((response) => { this.Collections = response.data.data this.disableButtons(response.data.data); }) .catch(function (error){ if(error.response.status === 422){ self.$router.push({name: "Settings"}); } }); },