반응형
개발 중 상태 변화에 따라서 자식 컴포넌트를 새롭게 렌더링 해야 할 필요가 있는 경우가 있습니다.
그럴 경우에 컴포넌트를 리렌더링 하는 방법 4가지를 설명드리겠습니다.
4가지 방법 중 가장 아래에 있는 key를 이용해서 리렌더링 하는 방법을 추천드립니다.
1. reload() 사용하기
화면을 새롭게 다시 그리는 방법입니다.
완전히 모든 컴포넌트와 화면을 다시 그리기 때문에 성능상으로 비효율적입니다.
<template>
<div>
<MyComponent></MyComponent>
<Button @click="reRender">Reload</Button>
</div>
</template>
<script>
import MyComponent from "../components/MyComponent.vue";
export default {
name: 'IndexPage',
components: {MyComponent},
methods: {
reRender() {
window.location.reload();
},
}
}
</script>
2. if문 이용하기
아래 코드의 동작 방식을 간단히 설명하면
1. v-if문을 이용해서 컴포넌트를 숨김
2. $nextTick을 이용해서 DOM을 업데이트 합니다.
3. 다시 컴포넌트를 생성하여 렌더링을 합니다.
<template>
<div>
<MyComponent v-if="isRender"></MyComponent>
<Button @click="reRender">$nextTick</Button>
</div>
</template>
<script>
import MyComponent from "../components/MyComponent.vue";
export default {
name: 'IndexPage',
components: {MyComponent},
data() {
return {
isRender: true,
}
},
methods: {
async reRender() {
this.isRender = false;
await this.$nextTick();
this.isRender = true;
}
}
}
</script>
3. $forceUpdate 사용하기
$forceUpdate를 이용해서 컴포넌트를 강제로 업데이트하는 방법이 있습니다.
이 방법의 경우 Vue에서도 공식적으로 지원하는 방법입니다.
하지만 Vue의 반응형 시스템에 대해서 제대로 반응하지 않을 수 있는 단점이 있습니다.
<template>
<div>
<MyComponent></MyComponent>
<Button @click="reRender">$forceUpdate</Button>
</div>
</template>
<script>
import MyComponent from "../components/MyComponent.vue";
export default {
name: 'IndexPage',
components: {MyComponent},
methods: {
reRender() {
this.$forceUpdate();
}
}
}
</script>
4. key 이용하기
컴포넌트의 key값의 변경이 되면 기존 컴포넌트는 삭제되고, 새로운 컴포넌트를 생성합니다.
아주 간단하게 컴포넌트를 재렌더링할 수 있습니다.
<template>
<div>
<MyComponent :key="key"></MyComponent>
<Button @click="reRender">key</Button>
</div>
</template>
<script>
import MyComponent from "../components/MyComponent.vue";
export default {
name: 'IndexPage',
components: {MyComponent},
data() {
return {
key: 0
}
},
methods: {
reRender() {
this.key++;
}
}
}
</script>
728x90
반응형