Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Today
Total
관리 메뉴

고리타분한 개발자

[Vue JS] Components 101 본문

Vue JS/Step By Step

[Vue JS] Components 101

sunlee334 2017. 12. 4. 19:03

때론 코드를 재사용할 일이 생기기도 합니다. 이번시간에는 components를 사용하는 방법에 대해 알아보겠습니다. 


<!-- index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title></title>

</head>

<body>
<div id="root">
<task></task>
<task></task>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<script src="main.js"></script>

</body>

</html>


// main.js
Vue.component('task', {
template: '<li>Foobar</li>'
})

new Vue({
el: '#root'
})


위에는 index.html과 main.js 두개의 코드가 있습니다. main.js는 index.html의 src로 연결 되어있죠. main.js를 보면 task라는 이름의 component가 정의되어 있습니다. 이 컴포넌트는 Foobar를 뿌려주는 template를 가지고 있습니다. 컴포넌트는 <componentName></componentName>과 같은 방법으로 사용할 수 있습니다. 

결과값은 아래와 같이 나오게 됩니다.


하지만 여기에는 한가지 흥미로운 사실이 있습니다. 


<div id="root">
<task></task>
<task>slot</task>
</div>


이렇게 컴포넌트명 사이에 slot이라는 단어를 추가해보도록 하겠습니다. 


하지만 결과값은 변화하지 않았습니다. 그럼, slot이라는 단어를 출력하기 위해서는 어떻게 해야할까요?


// main.js
Vue.component('task', {
template: '<li>Foobar <slot></slot></li>'
})

new Vue({
el: '#root'
})


main.js 로 돌아와서 slot이라는 옵션을 주게되면



slot이란 단어가 정상적으로 출력하는 것을 확인할 수 있습니다. 컴포넌트는 매우 중요한 개념이므로 컴포넌트에 관한 포스팅을 여러번에 걸쳐 나누어 진행해 보도록 하겠습니다.


Comments