Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- javscript
- 음양더하기
- sns로그인
- mixins
- axios
- programmers
- includes
- v-if
- IntelliJ
- 템플릿문법
- state
- Login
- v-for
- 콘솔한글깨짐
- node.js
- 연동
- v-on
- JavaScript
- Emit
- Vue.js
- Reduce
- azure
- vuex
- react
- javascipt
- Express.js
- kibana
- getters
- KAKAO
- mutations
Archives
- Today
- Total
공부용
[vue.js] 4. props와 emit 본문
0. 시작하기
부모에서 자식으로 데이터를 주는 props와
자식에서 부모에게 데이터를 주는 emit을 한번 사용해보려고 한다.
1. props
// src/components/props.vue
<template>
<div>
child counter : {{ counter }}
</div>
<button @click="addCounter">+</button>
<button @click="subCounter">-</button>
</template>
<script>
export default {
props:
["counter"]
}
</script>
props에서 부모에게서 받는 counter를 사용한다고 등록한다.
// src/view/props.vue
<template>
<div>
parent counter : {{ counter }}
</div>
<button @click="addCounter">+</button>
<button @click="subCounter">-</button>
<hr>
<props v-bind:counter="counter"/>
</template>
<script>
import props from '../components/props.vue';
export default {
data () {
return {
counter : 0
}
},
methods: {
addCounter : function() {
this.counter++;
},
subCounter : function() {
this.counter--;
}
},
components: {
props
}
}
</script>
script 단에서 components 폴더에 있는 props.vue 파일을 import 시킨 후,
components 에서 props를 사용한다고 등록한다.
그후 template에서 props라는 태그를 적어준 뒤 v-bind로 counter를 전달한다.
parent counter의 +버튼을 누르면 child counter도 숫자가 따라서 올라간다는걸 확인 할 수 있다.
2. emit
// ./src/view/emit.vue
<template>
<div>
parent counter : {{ counter }}
<hr>
<emit @setCounter="counterChange"/>
</div>
</template>
자식태그에서 자식이 호출한 함수를 어떤식으로 펑션으로 사용할지에 대해 적는다.+
<script>
import emit from '../components/emit.vue';
export default {
data () {
return {
counter : 0
}
},
methods: {
counterChange(counter) {
this.counter = counter
}
},
components: {
emit
}
}
</script>
methods단에서 사용하는 펑션을 이용해서 counter를 받아와 this.counter로 넘겨준다.
./src/components/emit.vue
<template>
<!-- 자식 -->
<div>
child counter : {{ counter }}
<br>
<button @click="addCounter">+</button>
<button @click="subCounter">-</button>
</div>
</template>
<script>
export default {
data () {
return {
counter : 0
}
},
methods: {
addCounter : function() {
this.counter++;
this.$emit('setCounter', this.counter);
},
subCounter : function() {
this.counter--;
this.$emit('setCounter', this.counter);
}
}
}
</script>
html에 click을 누르면 펑션을 이동하게끔 만들어준다.
method 단에서 this.$emit(호출 함수, 전달 변수)를 적어준다
child counter 버튼을 누르면 숫자가 parent도 증감되는것을 확인할 수 있다!
'공부용 > vue.js' 카테고리의 다른 글
[vue.js] 6. mixins (0) | 2022.02.21 |
---|---|
[vue.js] 5. vuex (0) | 2022.02.21 |
[vue.js] 3-2 v-if 와 v-on (0) | 2022.02.16 |
[vue.js] 3-1. vue 템플릿 문법 및 v-for (0) | 2022.02.16 |
[vue.js] 2. router (0) | 2022.02.16 |
Comments