💡 가상돔(Virtual DOM) 한줄 정리!
- 가상돔은 HTML 뷰에 변화가 있을 때, 이전의 가상돔과 새로운 가상돔을 비교해 변경된 내용만 감지해 DOM에 적용하는 것을 말한다.
<div id="app">
<h1>회원가입</h1>
<form class="form">
<input type="text" placeholder="아이디를 입력하세요" />
<input type="password" placeholder="비밀번호를 입력하세요" />
<button type="submit">저장</button>
</form>
<div>
<button type="button" class="button">로그인</button>
</div>
</div>
function h(type, props, ...children) {
return { type, props , children: children.flat() }
}
h('div', {id: 'app'},
h('h1', null, '회원가입'),
h('form', {className: 'form'},
h('input', {type: 'text', placeholder: '아이디를 입력하세요'}),
h('input', {type: 'password', placeholder: '비밀번호를 입력하세요'}),
h('button', {type: 'submit'}, '저장')
),
h('div',
h('button', {type: 'button', className: 'button'}, '로그인')
);
{
"type": "div",
"props": {
"id": "app"
},
"children": [
{
"type": "h1",
"props": null,
"children": []
},
{
"type": "form",
"props": {
"className": "form"
},
"children": [
{
"type": "input",
"props": {
"type": "text",
"placeholder": "아이디를 입력하세요"
},
"children": []
},
{
"type": "password",
"props": {
"placeholder": "비밀번호를 입력하세요"
},
"children": []
},
{
"type": "button",
"props": {
"type": "submit"
},
"children": [
"저장"
]
}
]
},
{
"type": "div",
"props": null,
"children": [
{
"type": "button",
"props": {
"type": "button",
"className": "button"
},
"children": [
"로그인"
]
}
]
}
]
}
위와 같이 실제 DOM 트리를 가상 DOM으로 바꾸는 작업을 해보았는데, 사실 큰 기술이라기 보다는 그저 DOM 구조를 가져다가 JS 객체로 만들어준 것이다.
참고한 글
Vanilla Javascript로 가상돔(VirtualDOM) 만들기
Virtual DOM(버추얼 돔,가상 돔)을 직접 만들어보자