반응형
SMALL
Component
기본 엘리먼트를 확장하여 재사용 가능한 코드를 캡슐화 시킨다.
html이 중복되서 같은 코드를 반복 할 때 그 코드를 그대로 html에 두지말고 컴포넌트를 하나 생성해서
그 안에다가 선언해주면 된다.
Vue 컴포넌트는 Vue 인스턴스이기도 하다.
따라서 모든 옵션 객체를 사용할 수 있다.(루트에만 사용하는 옵션은 제외)
그리고 같은 라이프사이클 훅을 사용할 수 있다.
컴포넌트 사용하기
1. 전역등록
Vue.component('example-component',{
//옵션
})
이렇게 등록 한 후
2. 컴포넌트는 인스턴스에서 커스텀 엘리먼트로 사용이 가능하다.<example-component></example-component>
<div id="example">
<example-component></example-component>
</div>
//등록하기
Vue.component('example-component',{
template:'<div>사용자 정의 컴포넌트</div>'
})
//루트 인스턴스 생성
new Vue ({
el:'#example'
})
//////////이후 아래와 같이 랜더링 됨///////////
<div id="example">
<div>사용자 정의 컴포넌트 입니다!</div>
</div>
실습하기
<div id="root"> <!--각 word-replay 들은 각각 다른 데이터를 가진다. data 에서 한번 return해서 값을 받아오기 때문ㄴ-->
<word-replay></word-replay>
<word-replay></word-replay>
<word-replay></word-replay>
</div>
<script>
Vue.component('word-replay', { //전역 컴포넌트 선언
template: ` // template 사용시 큰 부모로 무조건 한번 감싸줘야한다.
<div>
<div>{{word}}</div>
<form v-on:submit="onSubmitForm">
<input type="text" v-model="value" ref="answer">
<button type="submit">입력</button>
</form>
<div>{{result}}</div>
</div>
`,
data(){
return{
word:'안녕',
result:'',
value:'',
};
},
methods:{
onSubmitForm(e){
e.preventDefault();
if(this.word[this.word.length - 1] === this.value[0]){
this.result = '딩동댕';
this.word = this.value;
this.value = '';
this.$refs.answer.focus();
}else{
this.result = '땡';
this.value = '';
this.$refs.answer.focus();
}
}
},
})
const app = new Vue ({ //Vue한테 태그 통제권을 넘기겠다는 뜻
el : '#root',
});
</script>
컴포넌트는 중복을 피하고 재사용하기 위해서 사용하지만 달라지는 부분들은 props로 넣어주면 된다.
반응형
LIST
'프론트엔드 > 뷰(Vue)' 카테고리의 다른 글
Vue3 Composition API와 기초 문법 다뤄보기(2) (4) | 2024.03.22 |
---|---|
Vue3 Composition API와 기초 문법 다뤄보기(1) (0) | 2024.03.20 |
visual studio에서 Vue 처음 셋팅해보기 (0) | 2023.09.06 |
Vue를 이용한 구구단 만들기 (v-on:submit, ref, v-model) (0) | 2023.09.04 |
Vue.js 기초셋팅 (0) | 2023.09.01 |