2022. 3. 18. 23:49ㆍVue
1. Props : 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달할 때 사용
부모 컴포넌트(Compo.vue 5번 줄)에는 자식 컴포넌트(Button.vue 6번 줄)에게 print 라는 키 값을 통해 값을 보내고 있다.
여기서 print은 key가 되고 parentText 는 value 값이 된다.
print를 키로 설정했다면 자식 컴포넌트에 등록 props { }을 해줘야 한다.
props: {
print: String,
},
// 자식 컴포넌트에서는 props: { }라는 곳에 해당 키를 등록하고 사용하면 된다.
2. Emit : 자식 컴포넌트에서 부모 컴포넌트로 데이터를 전달할 때 사용
Emit은 @setInput이라는 키를 등록하고 함수를 보내고 있다.
Emit은 내가 사용하고 싶은 부분에 this$. emit("키", 값) 형태로 데이터를 지정해주면 된다.
3. 주의사항
props 나 emit 을 사용할 땐 camel 표기법을 사용해선 안된다. kebab 표기법(xx-xx)를 사용한다.
이유 >> 컴포넌트 및 props와는 다르게 이벤트 이름은 자바스크립트 변수나 속성의 이름으로 사용되는 경우가 없으며,
따라서 camelCase나 PascalCase를 사용할 필요가 없다. 또한, (HTML의 대소문자 구분을 위해) DOM 템플릿의 v-on 이벤트 리스너는 항상 자동으로 소문자 변환되기 때문에 v-on:myEvent는 자동으로 v-on:myevent로 변환된다.
즉 myEvent 이벤트를 들을 수 없다.
Props 속성 이용하여 상위 > 하위 컴포넌트 데이터 전달
<!-- parentComponent -->
<template>
<div>
하위 컴포넌트에 데이터 값을 알려줍니다.
<ChildComponent v-bind:childVaule="parentVaule"/>
</div>
</template>
<script>
import ChildComponent from "@/components/childComponent.vue";
export default {
name: "ParentComponent",
components: {
ChildComponent
},
data() {
return {
parentVaule: 20,
};
},
};
</script>
// 배열로 받는 방법
props: ["childVaule"],
// 객체로 받는 방법
props: {
childValue: {
type: Number
}
}
v-bind:하단 컴포넌트에서 받을 props 이름을 사용하여 하단 컴포넌트에서 데이터를 전달 받을 수 있다.
v-bind는 생략 가능하며 하단 컴포넌트에서 받을 props 이름'로 사용해도 된다.
Emit 속성 이용하여 하위 > 상위 컴포넌트 데이터 전달
<!-- parentComponent -->
<template>
<div>
<ChildComponent v-on:childEvent="updateParentValue"/>
</div>
</template>
<script>
import ChildComponent from "@/components/childComponent.vue";
export default {
name: "ParentComponent",
components: {
ChildComponent
},
data() {
return {
parentVaule: 20,
}
},
methods: {
updateParentValue() {
this.parentVaule++;
console.log(this.parentVaule) // 21, 22, 22, 누를때마다 증가하는 것 확인 가능//
},
},
};
</script>
<!--childComponent-->
<template>
<button @click="updateParentValue">
클릭시 부모의 데이터 값이 증가합니다.
</button>
</template>
<script>
export default {
name: "ChildComponent",
methods: {
updateParentValue() {
this.$emit("childEvent");
},
},
};
</script>
https://developerjournal.tistory.com/4
쟈쟈, 차근차근 곱씹어 보도록 하쟘
prop 는 부모에서 값을 가져오는 거잖아????
num에다가 number(1)을 값을 붙여서 델꼬오쟈!
그래서 자식 BoardChild한테 가보니 1이 찍히는 고지! ㅇ-ㅇ 끝 !
그럼 자식이 클릭했을 때의 변경해야하는 값을 부모한테 넘기도록 하ㅈㅑ~
부모님 받으세요 하는걸 $emit으로 알려줍니다~
부모한테 도오착! @up ="update" 메소드안에서 숫자를 증가해준다~ ㅇ-ㅇ 끝 !
원래는 자식한테 text를 넘겨주는게 맞다. 근데 study를 써도 나오는 이유는
data()에서 study: this.text라고 데이타를 주었기 때문에 값이 잘나옴 !!!
후 첨알앙네
--------------------------------------------------------------------------------------------------------
댓글에 이미지 첨부가 안되어서 여기에 남깁니다!
'Vue' 카테고리의 다른 글
Vue Router - prefetch, Lazy Loading(지연된 로딩) (0) | 2022.04.07 |
---|---|
[Vue-Project] Todo-App (0) | 2022.04.01 |
[Vue] Slot (0) | 2022.03.17 |
[Vue] 인코딩 / 디코딩 (0) | 2022.03.15 |
v-for (0) | 2022.03.14 |