this.$router.push(동일path)일 경우 에러가 나고 새로 고침을 하자니 SPA페이지에서 낭비인 것 같기도 해서

어떤 방식을 써야하나? 고민을 하다가 찾은 방식. (기록을 위한 작성)

검색하다가 알게된 블로그에서 3가지 방식을 알려주고 있었다. 

v-if 방식, forceUpdate 방식, 그리고 key를 통한 방식.

가장 추천하는 방식으로 (vue가 원하는..?) 진행했다.

 

레이아웃 단계에서 진행.

base-header 컴포넌트에 gnb가 있으며  nuxt 컴포넌트는 페이지이다. 

// BaseLayout.vue
<template>
	<div>
    	<base-header @forceUpdate="handleForceUpdate"/>
    </div>
    <div>
    	<Nuxt :key="componentRenderKey"/>
    </div>
    <div>
    	<base-footer />
    </div>
</template>

<script>
export default {
  name: 'BaseLayout',
  data() {
    return {
      componentRenderKey: 0,
    }
  },
  methods: {
  	handleForceUpdate() {
      // 키 값이 올라가면서 :key의 값이 변하여 Nuxt가 리렌더링된다. 
      this.componentRenderKey = this.componentRenderKey + 1;
      // 이때 스크롤까지 초기화되는 것은 아니므로 top으로 올려주기
      window.scroll(0, 0);
    },
  }
}
</script>

 

// base-header.vue
<template>
	<header>
    	<ul>
        	<li v-for="nav in gnb">
            	<nuxt-link 
                  :to="nav.path" 
                  @click.native="() => handleForceUpdate(nav.path)"  
                >
                  {{nav.name}}
                </nuxt-link>
            </li>
            // ....
        </ul>
    </header>
</template>

<script>
export default {
  name: 'BaseHeader',
  methods: {
	handleForceUpdate(to) {
      if (to === this.$route.path) {
        // 상위컴포넌트(Base Layout)로 이벤트 발생 (emit)
        this.$emit('forceUpdate');
      } else {
        this.$router.push(to);
      }
    }
  }
}
</script>

 


* 출처: 3가지 방식을 안내해줌

https://michaelnthiessen.com/force-re-render/

 

+ Recent posts