캡틴판교 장기효님의 Vue.js시작하기 인프런 강의를 수강하고 내용을 정리했다.
매일 20분 야금야금 Vue.js 화이팅.
IDE: Visual Studio Code
크롬 뷰 개발자 도구: Vue.js devtools
싱글 파일 컴포넌트에서 props 속성와 event emit 을 구현해보자.
실습 코드는 이전 포스팅에서 만든 것을 바탕으로 하고 있다.
상위 컴포넌트 App
하위 컴포넌트 AppHeader
App 컴포넌트의 문자열 데이터를 하위 컴포넌트인 AppHeader 컴포넌트로 내리자.
'Header'라는 문자를 내리고 싶다.
data 속성에 str이라는 이름으로 정의하자.
<script>
import AppHeader from './components/AppHeader.vue'
export default {
data: function(){
return {
str: 'Header'
}
},
components: {
'app-header': AppHeader
}
}
</script>
컴포넌트 구조에서 확인한 것 처럼, 상위 컴포넌트는 하위 컴포넌트를 갖고 있다.
v-bind로 props 속성에 data를 바인딩 하자.
props 속성 이름은 propsdata로 지었다.
<하위 컴포넌트명 v-bind:프롭스 속성="데이터"></하위 컴포넌트명>
<template>
<div>
<app-header v-bind: 하위 컴포넌트의 프롭스 속성 이름="상위 컴포넌트의 데이터 이름"></app-header>
<app-header v-bind:propsdata="str"></app-header>
</div>
</template>
하위 컴포넌트가 데이터를 내려받는 것이기 때문에, 하위 컴포넌트 태그에 props를 작성한다는걸 기억하자.
props 속성에 propsdata 라는 이름으로 정의하자.
<template>
<header>
<h1>{{ propsdata }}</h1>
</header>
</template>
<script>
export default {
props: ['propsdata']
}
</script>
<style>
</style>
하위 컴포넌트에서 버튼을 클릭해서 상위 컴포넌트로 emit을 보내면, propsdata를 바꿔보자.
버튼에 v-on 디렉티브를 만들고 sendEvent라는 메서드를 실행하는 click 이벤트를 정의한다.
<template>
<header>
<h1>{{ propsdata }}</h1>
<button v-on:click="sendEvent">send</button>
</header>
</template>
sendEvent 라는 메서드를 만든다.
<script>
export default {
props: ['propsdata'],
methods: {
sendEvent: function(){
}
}
}
</script>
sendEvent 메서드에 emit을 정의한다.
'renew'라는 emit을 올리면, props속성으로 내리는 propsdata를 변경해보자.
<script>
export default {
props: ['propsdata'],
methods: {
sendEvent: function(){
this.$emit('renew')
}
}
}
</script>
하위 컴포넌트의 renew 이벤트가 올라오면, 상위 컴포넌트에서는 renewStr 메서드를 실행하자.
v-on:event-emit이름="메서드 이름"
app-header 태그에 추가할 코드는 아래와 같다
<template>
<div>
<app-header
v-bind:propsdata="str"
v-on:renew="renewStr"
></app-header>
</div>
</template>
renewStr 메서드는 str 문자열을 'hi'로 바꾼다.
methods: {
renewStr: function(){
this.str = 'hi';
}
}
app-header 에 의해 $emit이 발생한 renew 이벤트임이 보인다.
새로고침 누르고, 'send'버튼을 눌러보면 propsdata가 Header에서 hi로 변한 것이 보인다.
터미널에서 ctrl + c로 시그널을 보내 종료시키면 된다.
참고로 ctrl + z 시그널은 일시중지(suspended)이기 때문에 종료가 아니다.
<template>
<div>
<!-- <app-header v-bind: 하위 컴포넌트의 프롭스 속성 이름="상위 컴포넌트의 데이터 이름"></app-header> -->
<app-header
v-bind:propsdata="str"
v-on:renew="renewStr"
></app-header>
</div>
</template>
<script>
import AppHeader from './components/AppHeader.vue'
export default {
data: function(){
return {
str: 'Header'
}
},
components: {
'app-header': AppHeader
},
methods: {
renewStr: function(){
this.str = 'hi';
}
}
}
</script>
<style>
</style>
<template>
<header>
<h1>{{ propsdata }}</h1>
<button v-on:click="sendEvent">send</button>
</header>
</template>
<script>
export default {
props: ['propsdata'],
methods: {
sendEvent: function(){
this.$emit('renew')
}
}
}
</script>
<style>
</style>
다음 시간에는 기본 강의의 마지막인 '사용자 입력 폼'을 만들어본다.