2018-08-01 Vue JS-컴포넌트 속성 data / props / watch / computed / event bus
컴포넌트 속성(option) - data / props / watch / computed / event bus
- 컴포넌트의 옵션은 문자열, 숫자, 함수, 객체 리터럴 중 하나를 값으로 사용.
data() - 옵션 함수
- 컴포넌트의 상태 정보를 저장하기 위해, data 옵션을 사용한다.
- data 옵션에 함수를 지정하는 이유는 동일한 컴포넌트가 여러 번 사용될 경우, 동일한 객체를 가리키는 것이 아니라 함수가 호출될 때마다 만들어진 객체가 리턴 되기 때문.
data: {
num: 1
}
or
data () {
return {
num: 1
}
}
함수 내부에서, 객체를 리턴한다.
- Main.vue 작성
<template>
<div>
<hr>
<span>data() 옵션 -> msg : </span>
<hr>
<Example1></Example1>
</div>
</template>
<script>
import Example1 from './example/Example1.vue'
export default {
name: 'Main',
data () {
return {
msg: 'vue-sample-project'
}
},
components: {Example1}
}
</script>
<style scoped>
</style>
props
- 부모 컴포넌트에서 자식 컴포넌트로 데이터를 내려주기 위해 사용.(단방향)
- 컴포넌트 태그의 속성 이름을 리터럴 배열로 정의
- Example1.vue 작성
<template>
<div>
msg:
<Module1 v-bind:super-msg="msg"></Module1>
<Module2></Module2>
</div>
</template>
<script>
import Module1 from './Module1.vue'
import Module2 from './Module2.vue'
export default {
name: 'Example1',
data () {
return {
msg: 'vue JS 예제 작성'
}
},
props: ['superMsg'],
template: '',
components: {
Module1,
Module2
}
}
</script>
<style scoped>
</style>
- Module1.vue 작성
<template>
<div>
<h3>Module 1 : data, props 옵션</h3>
<span>welcomeMsg : </span>
<br>
<span>Example1 msg(props) : </span>
</div>
</template>
<script>
export default {
name: 'Module1',
data () {
return {
welcomeMsg: 'data() 옵션 welcomeMsg'
}
},
props: {
// title: String
superMsg: {
type: String,
required: true
}
}
}
</script>
<style scoped>
h3 {
color: skyblue;
}
</style>
위와 같이, 객체 리터럴로 설정이 가능하기도 하다.(데이터 타입, 유효성 등을 체크)
watch - 옵션 객체
- 컴포넌트의 상태값이 변할 때, 변경을 감지하여 다른 작업을 할 때 흔히 사용
- 객체 리터럴로 설정
<template>
<div>
<h3>Module 2 : life cycle(개발자 도구를 켜보자)</h3>
<span v-text="eventCount"></span>
<br>
<span></span>
<button @click="printEvent">printEventCount</button>
</div>
</template>
<script>
export default {
name: 'Module2',
data () {
let eventCount = 1
return {
eventCount
}
},
methods: {
printEvent: function () {
console.log('버튼을 눌렀습니다.')
alert(this.eventCount)
this.eventCount++
}
},
watch: {
eventCount: function () {
alert('값 변경 감지 : ' + this.eventCount)
}
}
}
</script>
<style scoped>
h2{
color: red;
}
</style>
----
watch: {
eventCount: function (newValue, oldValue) {
//상태 값이 변경 되었을 때, 할 일
}
}
감시할 속성은 watch 옵션 객체의 속성 이름에 기록하고, 감시자 속성의 변경 이후 값과 이전 값을 전달받는 함수를 속성 값으로 정의.
computed(계산된 속성) - 옵션 객체
- 컴포넌트에 읽기 전용 속성을 만듬
- 객체 리터럴로 설정
- computed name 은 component 템플릿에서 참조할 상태 값의 이름
- 인자를 받지 않는 함수를 선언
- get / set 을 지정하면, 쓰기 작업도 가능
Vue.component('static-component', {
template: '<h4>static-component => reverse Msg : </h4>',
data: function () {
return {
sMsg: 'static!!'
}
},
computed: {
reverseMsg: function () {
return this.sMsg.split('')
.reverse()
.join('')
}
}
})
event bus
- props 또는 event를 통해, 부모-자식 컴포넌트간에 데이터를 주고 받을 수 있는데.. 문제는 단방향이고.. 저 멀리 떨어진 컴포넌트와 통신을 하려면.. 줄기를 쭈욱 타고 가야하는데.. 이것을 해결하기 위해 event bus를 사용한다.
- 비어있는, Vue 인스턴스를 생성하여 사용
- 이벤트를 수신하는 컴포넌트는 미리 이벤트 핸들러를 등록($on) : 이를 위해, Vue 생명주기의 created 훅을 이용해 $on을 등록
Single File Component 로 구성된, Vue 프로젝트에서는 EventBus를 어떻게 정의하지?
EventBusExample.js 작성
/**
* eventBus 객체 생성
* eventBus 는 비어있는, Vue 인스턴스를 만들어서 사용
*/
import Vue from 'vue'
export const EventBus = new Vue()
사용은 매우 간단
서로 통신하고자 하는 컴포넌트에서 정의해서 사용하면 된다.
//보내기
import {EventBus} from './EventBusExample.js'
sendData: function () {
EventBus.$emit('receiveTest', 'Module2에서 보내는 Msg')
}
//받기
import {EventBus} from '../../EventBusExample.js'
export default {
name: 'Module3',
created: function () {
EventBus.$on('receiveTest', this.printMsg)
},
methods: {
clickTest: function () {
this.$emit('childReceive', this.test)
},
printMsg: function (msg) {
alert(msg)
}
},
props: ['test', 'num']
}
- $on(eventName, value1, ..) : 이벤트 감지
- $emit(eventName, callback()) : 이벤트 트리거
Comments