현재 프론트에서 아래와 같은 에러가 콘솔에 출력된다.
이는 프론트에서 같은 페이지로 router.push('path')
를 하게될때 발생하며 예를들어 메인페이지에서 헤더의 메인페이지로 이동하려고 할때 위와같은 에러가 출력된다.
$router.push()
의 에러핸들링을 안해줘서 기본으로 콘솔에 에러가 찍힌다. catch문으로 위 에러를 잡아주면된다.
this.$router.push('/')
에서
this.$router.push('/').catch(()=>{});
로 catch만 추가해주면된다.
하지만 이방법으로 하면 $router.push()
가 사용되는 코드 전부 catch문을 붙여줘야한다. 중복이 싫으니 전역으로 세팅하는 방법을 찾자.
router/index.js 파일에서 아래와 같이 수정해주면 다른 파일들에서 $router.push
를 사용할 때 catch를 붙여주지 않아도 되서 간결하게, 코드 중복을 줄이며 해결할 수 있다.
import Vue from 'vue';
import VueRouter from 'vue-router';
import { UserService } from './../service/user.service';
import store from './../store';
Vue.use(VueRouter);
...(생략)
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => {
if (err.name !== 'NavigationDuplicated') throw err;
});
};
export default router;
1번 방법은 에러를 전부 무시하는 코드지만, 2번방법은 NavigationDuplicated 에러만 무시하는 코드이다.
stackoverflow-Getting navigation duplicated error while the route is being replaced on Vue-Router