-
Vue / 9강 ~ 11강 / Component Life Cycle, DirectiveDEV/Vue 2022. 7. 15. 22:28728x90반응형
Vue / 7강, 8강 / Component의 기본, Data Binding
https://ccamanglab.tistory.com/25 Vue / 1~6강 / 프론트엔드 프레임워크와 ES6 프론트엔드 개발자를 위한 Vue.js 시작하기 강의를 들으며 정리한 내용 1강 프론트엔드 웹 어플리케이션 서버 사이드 도움 받지
ccamanglab.tistory.com
에 이어서 작성

[Component Life Cycle]
컴포넌트는 생성부터 소멸까지 일련의 LifeCycle을 거침
ex
{ data(){ return {count:1} }, created(){ console.log('count is: '+this.count) } }1.Create
컴포넌트가 생성되는 단계이며 DOM에 추가되지 않은 단계
beforeCreate() 함수와 created() 함수를 선언할 수 있음
beforeCreate() data 와 events가 준비되지 않은 상태
created() data, computed, methods, watch 등이 준비된 상태
Create 단계에서는 Mount가 되지 않은 상태로, $el을 사용할 수 없음
2.Mount
컴포넌트의 DOM을 준비하여 화면에 출력되는 단계
beforeMount(), mounted()함수가 호출됨
beforeMount() Mount가 시작되기 직전에 호출됨
mounted() Mount가 완료된 후 호출됨, $el로 Component DOM에 접근할 수 있음
3.Update
화면 출력이 변경될 때 호출됨(리렌더링)
beforeUpdate(), updated() 함수가 호출됨
beforeUpdate() 데이터 변경되기 전에 호출됨
update() 데이터 Update가 완료된 후 호출됨
4.Destroy
컴포넌트의 소멸 단계
beforeUnmount()와 unmounted()함수가 호출됨
[Props]
상위 컴포넌트가 전달한 데이터임
상위 컴포넌트에서 하위 컴포넌트를 이용할 때 속성으로 추가한 데이터임
props option
상위에서 속성으로 추가한 데이터를 받기 위한 옵션
상위에서 사용한 속성명을 props에 등록
props내에 상위의 속성 값이 자동 대입되어 이용됨
상위 컴포넌트 <Component2 attr1="hello" attr2="10" attr3="true"></Component2> 하위 컴포넌트 export default { props : ['attr1','attr2','attr3'] }<template> <div> I am sub component! <br/> super data : {{message}} <br/> attr1 : {{attr1}}, attr2 : {{attr2}}, attr3:{{attr3}} </div> </template> <script> export default{ props: ['attr1','attr2','attr3'], data(){ return { message : this.attr1 + ':' + this.attr2 + ':' + this.attr3 }}} </script>Type 지정
props로 전달되는 데이터의 Type 지정
Object Literal로 props선언하면서 Value에 Type 지정
//String, Number, Bollean, Array, Object, Function 등 props : { attr1 : { type : String}, attr2 : { type : Number}, attr3 : { type : Boolean}, }상위 함수 호출
하위 컴포넌트에서 상위 컴포넌트의 함수 호출
상위 컴포넌트에서 속성으로 함수를 전달
하위 컴포넌트에서 $props를 이용해 상위 함수 호출
상위 컴포넌트 <Sub v-bind:attr4="superMethod"></Sub> ... methods:{ superMethod : function () { console.log("method function call... ")}} 하위 컴포넌트 props:{ attr4:{type : Function }, data(){this.$props.attr4()}required
필수 전달 데이터도 지정
Props에 required:true 지정
props:{ attr3:{type : Boolean, required:true}}
[Directive]
컴포넌트는 동적 UI 구성을 목적으로 하며 태그로 이용됨
Directive는 속성으로 이용되며 속성이 적용된 DOM에 대한 추가 작업을 목적으로 함
Vue.js에서 제공하는 Directive가 있으며, 개발자가 직접 만들어 사용할 수 있음
<div v-show="false">I am Show </div>[Custom Directive]
Custom Directive는 오브젝트 리터럴로 만들어짐
디렉티브의 라이프 사이클 함수를 이용해 Directive에서 실행할 로직을 담음
var testDirective = { mounted(el){ el.focus() } }[Directive Lifecycle]
Directive의 Lifecycle은 Directive가 사용되는
Element(Component)의 Lifecycle과 유사하지만 차이가 있음
beforeMount() Directive가 Element에 바인딩 되면 호출되며 한 번만 호출됨
mounted() Element가 부모 DOM에 삽입되면 호출
beforeUpdate() Element가 업데이트 되기 전에 호출
updated() Element가 업데이트 되면 호출
beforeUnmount() Element가 마운트 해제되기 전에 호출
unmounted() Directive가 Element에서 제거되면 호출
[el]
Lifecycle 함수의 매개변수로 전달
Directive가 사용된 Element 객체
el 객체를 이용해 Directive가 적용된 Element의 조작 작업 가능
mounted(el) { el.innerHTML = ` el.tagName : ${el.tagName} <br/> el.parentNode.tagName : ${el.parentNode.tagName}<br/> ` }[binding]
Lifecycle 함수의 매개변수로 전달
Directive와 관련된 다양한 정보 추출이 가능함
value - Directive에 대입된 값
oldValue - 변경되기 전의 값, beforeUpdate()와 updated()에서만 사용 가능
arg - Directive에 적용된 인자
modifiers - Directive에 적용된 수식어를 포함하는 객체
mounted(el, binding){ el.innerHTML = ` binding.value : ${binding.value}<br/> binding.arg : ${binding.arg} <br/> binding.modifires : ${JSON.stringify(binding.modifiers)} ` }[Directive의 Global 등록]
application instance에 Directive등록
application 전역에서 Directive 이용
application instance의 directive() 함수로 등록
첫 번째 매개변수가 Directive 속성명 var app = createApp(MyComponent) app.directive('testDirective',TestDirective) app.mount('#app') 등록된 Directive 이용 <template> <div> <input v-testDirective /> </div> </template>[Local 등록 사용]
Directive가 필요한 Component에 등록 사용
Component의 directives 속성을 이용해 등록
export default { data() { return { msg : "hello", data1 : 10}; }, directives: { myDirective}};
[Built in Directive]
1.v-bind
Component의 속성 혹은 Class 값을 바인딩 하기 위한 Directive
2.class 바인딩
v-bind를 이용하여 css class 및 style 등록
v-bind:class="{className : data}"
// data가 true 면 class 추가되며 false면 추가되지 않음 <div v-bind:class="{active : isActive}"></div> ... data(){ return { isActive : true} } //output <div class="active></div>객체 바인딩
<div v-bind:class="classObject"></div> ... classObject:{ 'active':true, 'text-danger':true} //<div class="active text-danger"></div>3항 연산자 이용 바인딩
<div v-bind:class="[isActive ? activeClass : errorClass]"></div>축약형으로 바인딩
v-bind는 콜론으로 이용 가능함
<a v-bind:href="url">google</a> <a :href="url">google</a>3.v-if
값이 true 면 출력, false 면 출력 x
v-else, v-else-if 와 같이 사용 가능
<div v-if="type === 'A'">A</div> <div v-else-if="type === 'B'">B</div> <div v-else-if="type === 'C'">C</div> <div v-else>Not A/B/C</div>4.v-show
v-if와 동일
display style 값 변경으로 화면에 출력을 제어함
v-else와 같이 사용하지 못함
template 태그에 사용할 수 없음 <div v-show="false">I am Show</div> //<div style = "display:none;">I am Show </div>[if 와 show의 차이]
v-if는 false일 경우 아예 렌더링 자체를 안함
v-show의 경우 dom을 만들어 놓고 css style을 보이지 않게끔 하는 것임
5.v-for
반복 출력
v-for="item in items"
v-for Directive가 사용된 Element에는 v-bind:key가 선언되어 있어야함
<li v-for="item in items" : key="item"> {{item.message}} </li>index값 추출
<li v-for="(item, index) in items" : key="index> {{ index }} - {{ item.message }} </li>Object Literal를 v-for에 사용하면 객체의 멤버들을 iterator 해줌
<li v-for="value in object" : key = "value"> {{ value }} </li> ... objcet : { firstName: 'Jhon', lastName : 'Doe', age:30 }idx,key,val
<li v-for="(value, key, index) in object" : key="index"> {{ index }} - {{ key }} : {{ value }} </li>range
<span v-for="n in 2" : key = "n"> {{ n }} - Hello <br/> </span>1.v-on
이벤트(Event) 바인딩
v-on:click="someFunc"
축약으로 @click="someFunc" 도 사용 가능
<button v-on:click="greet">Greet</button> ... methods: { greet: function(event) ... }{화면에서 이벤트에 의해 데이터 발생} -> {로직 실행을 위한 함수 호출} -> {매개 변수로 값 전달}
parameter 전달
<button v-on:click="warn('hello, $event)"> Submit </button> ... methods : { warn : function (message, event) { if (event) event.preventDefault() } }2. Event Modifier
다양한 modifier 등록으로 쉽게 이벤트 제어 가능
<form v-on:submit.prevent="onSubmit"></form>.stop event.stopPropagation()
.prevent event.preventDefault()
.capture 이벤트를 capture 하겠다는 의미
하위 element에서 이벤트가 발생하여도 capture가 선언된 곳에서 이벤트를 먼저 처리하기 위해 사용
.self 자신에게 발생한 이벤트만 처리하겠다는 의도
.once 한번만 이벤트 허용
이벤트 수식을 등록하면서 chain 형태로 여러 개 등록 가능
<a v-on:click.stop.prevent="doTaht"></a>3.Key Modifier
키 이벤트 처리 시 이벤트가 발생한 key 지정
<input @keyup.enter="keyEvent">4.v-model
Two-way Data Binding
<input v-model="name" palceholder="input name">checkbox의 경우 v-model에 의해 바인딩 되는 데이터는 true/false임
여러 개의 checkbox가 있고 check 된 value 값을 문자열 배열로 저장하는 것도 가능
<input type="checkbox" value="kkang" v-model="checkedNames"> <input type="checkbox" value="lee" v-model="checkedNames"> <input type="checkbox" value="park" v-model="checkedNames">반응형'DEV > Vue' 카테고리의 다른 글
Vue / 13강, 14강 / Vuex (0) 2022.07.17 Vue / 12강 / Router, SPA (0) 2022.07.16 Vue / 7강, 8강 / Component의 기본, Data Binding (0) 2022.07.15 Vue / 1~6강 / 프론트엔드 프레임워크와 ES6 (0) 2022.07.14