Vue Component를 리렌더 하는 방법을 찾다가 정리하기 위해 적는 글

v-if 이용하기

v-if directive를 이용해 해당 페이지를 보이게 했다 안보이게 함으로써 페이지를 렌더링할 수 있다. v-if 값을 data 연동하며 변경되도록 만들어준다.

이는 $nextTick() 메서드를 이용해 v-if 값을 갱신한다.

**$nextTick()**은 Dom이 렌더링 되는 이후에, 실행되는 콜백을 달아줄 수 있도록 하는 함수이다.

<script>
  export default {
    data() {
      return {
        renderComponent: true,
      };
    },
    methods: {
      forceRerender() {
        // Remove my-component from the DOM
        this.renderComponent = false;

        this.$nextTick(() => {
          // Add the component back in
          this.renderComponent = true;
        });
      }
    }
  };
</script>

하지만 v-if를 이용한 방법은 좋지 않다.

$forceUpdate() 이용하기

Vue에서 기본으로 제공해주는 함수로, 자기 자신 그리고, slot으로 들어간 자식 컴포넌트들만이 리렌더링 된다. 고로 slot 아닌 컴포넌트는 다시 렌더링 되지 않는다.

:key 이용하기

Vue에서는 key attribute를 통해서 특정 컴포넌트가 특정 데이터와 연결되어있다는 것을 식별한다. 이 key가 변경되게 되면, 새로운 컴포넌트를 생성해야한다는 것을 Vue가 인지한다.

해당 key 값이 바뀌게 되면 컴포넌트는 해당 child component를 re-init 후 해당 state를 재설정해준다. (근데 이게 v-if랑 뭐가 다른건지.. 잘은 모르겠다)

확인을 해보니 key값을 조작하게 되면 동일하게 create / mount / update를 전부 해주는 것 같다. v-if랑 큰 차이가 있나..

<aside> 💡 The key special attribute is primarily used as a hint for Vue’s virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list. Without keys, Vue uses an algorithm that minimizes element movement and tries to patch/reuse elements of the same type in-place as much as possible. With keys, it will reorder elements based on the order change of keys, and elements with keys that are no longer present will always be removed/destroyed.

</aside>

관련 자료를 보니 force replacement를 위해서 key를 사용하기도 한다고 써있다.