<1108 내용 정리> Vue - 5

백지윤·2023년 11월 8일
0

Vue

목록 보기
5/6
post-thumbnail

Passing Props

  • 부모는 자식에게 데이터를 전달(Pass Props)하며, 자식은 자신에게 일어난 일을 부모에게 알린다(Emit event)

- Props

  • 부모 컴포넌트로부터 자식 컴포넌트로 데이터를 전달하는데 사용되는 속성

- One-Way Data Flow

  • 모든 props는 자식 속성과 부모 속성 사이에 하향식 단방향 바인딩(one-way-binding)을 형성

특징

  • 부모 속성이 업데이트되면 자식으로 흐르지만 그 반대는 안된다.
  • 즉, 자식 컴포넌트 내부에서 props를 변경하려고 시도해서는 안되며 불가능하다.
  • 또한, 부모 컴포넌트가 업데이트 될때마다 자식 컴포넌트의 모든 props가 최신값으로 업데이트 된다.
    • 부모 컴포넌트에서만 변경하고 이를 내려받는 자식 컴포넌트는 자연스럽게 갱신된다.
  • 단방향인 이유 : 하위 컴포넌트가 상위 컴포넌트의 상태를 변경해 앱에서의 데이터 흐름을 이해하기 어렵게 만드는것을 방지

App > Parent > ParentChild

  • App

  • Parent

  • ParentChild

props 선언

  • 부모 컴포넌트에서 보낸 props를 사용하기 위해서는 자식 컴포넌트에서 명시적인 props 선언이 필요하다

Props 작성

  • 부모 컴포넌트 Parent에서 자식 컴포넌트 ParentChild에 보낼 props 작성
<template>
	<div>
    	<ParentChild my-msg='message' />
    </div>
</template>

my-msg(prop이름) = "message" (prop 값)

선언 방식 2 가지

1. 문자열 배열을 사용한 선언

  • defineProps()를 사용하여 props를 선언
<!--ParentChild.vue-->

<script setup>
defineProps(['myMsg'])
</script>

2. 객체를 사용한 선언 < 권장 >

  • 객체 선언 문법의 각 객체 속성의 키는 props의 이름이 되며, 객체 속성의 값은 값이 될 데이터의 타입에 해당하는 생성자 함수(Number, String..)여야 한다.
<!--ParentChild.vue-->

<script setup>
defineProps({
	myMsg: String
})
</script>

prop 데이터 사용

  • 템플릿에서 반응형 변수와 같은 방식으로 활용
<!--ParentChild.vue-->

<div>
	<p>{{ myMsg }}</p>
</div>
  • props를 객체로 반환하므로 필요한 경우 JS에서 접근 가능
<script setup>
const props = defineProps({ myMsg: String })
conole.log(props) // {myMsg:'message'}
console.log(props.myMsg) // message

props 한단계 더 내려 보내기

  • ParentChild 컴포넌트를 부모로 갖는 ParentGrandChild 컴포넌트 생성 및 등록

  • 설정 후, ParentChild 컴포넌트에서 Parent로부터 받은 prop인 myMsg를 ParentGrandChild에게 전달한다.
<!--ParentChild.vue-->

<template>
	<div>
    	<p>{{myMsg}}</p>
        <ParentGrandChild :my-msg='myMsg' />
    </div>
</template>
<!--ParentGrandChild.vue-->

<template>
	<div>
    	<p>{{ myMsg }}</p>
    </div>
</template>

<script setup>
defineProps({
	myMsg: String,
})
</script>
  • v-bind를 사용한 동적 props 이용

Props Name Casing

  • 선언 및 템플릿 참조시 (->camelCase)
<p>{{myMsg}}</p>

defineProps({
	myMsg: String
})
  • 자식 컴포넌트로 전달시 (->kebab-case)
<ParentChild my-msg='message' />

Static props & Dynamic props

  1. Dynamic props 정의
<!--Parent.vue-->

import { ref } from 'vue'

const name = ref('Alice')

<ParentChild my-msg='message' :dynamic-props='name' />
<!--ParentChild.vue-->

defineProps({
	myMsg: String,
    dynamicProps: String,
})

<p>{{ dynamicProps }}</p>

Component Events

$emit()
: 자식 컴포넌트가 이벤트를 발생시켜 부모 컴포넌트로 데이터를 전달하는 역할의 메소드

emit 메소드 구조

$emit(event, ...args)

  • event
    • 커스텀 이벤트 이름
  • args
    • 추가 인자

event 발신 및 수신

  • $emit을 사용하여 템플릿 표현식에서 직접 사용자 정의 이벤트를 발신한다.
<button @click="$emit('someEvent')">클릭</button>
  • 그러면 부모는 v-on을 사용하여 수신할 수 있다.
<ParentComp @some-event='someCallback' my-msg='message' :dynamic-props='name' />

const someCallback = function () {
	console.log('ParentChild가 발생한 이벤트를 수신했어요')
}

emit 이벤트 선언

  • defineEmits()를 사용하여 명시적으로 발신할 이벤트를 선언할 수 있다.
  • script 에서 $emit 메서드를 접근 할 수 없기 때문에 defineEmits()는 $emit 대신 사용할 수 있는 동등한 함수를 반환한다.
<script setup>
const emit = defineEmits(['someEvent', 'myFocus'])

const buttonClick = function () {
	emit('someEvent')
}
</script>
  • 이벤트 선언 방식으로 추가 버튼 작성 및 결과 확인
<!--ParentChild.vue-->

<script setup>
const emit = defineEmits(['someEvent'])

const buttonClick = function () {
	emit('someEvent')
}
</script>

<button @click='buttonClick'>클릭</button>

이벤트 인자(Event Arguments)

  • 이벤트 발신시 추가 인자를 전달해 값을 제공할 수 있다.

  • ParentChild에서 이벤트를 발신하여 Parent로 추가인자를 전달한다.

<!--ParentChild.vue-->

const emit = defineEmits(['someEvent', 'emitArgs'])

const emitArgs = function ) {
	emit('emitArgs', 1,2,3)
}

<button @click='emitArgs'>추가 인자 전달</button>
  • ParentChild에서 발신한 이벤트를 Parent에서 수신
<!--Parent.vue-->

<ParentChild
	@some-event='someCallbakc'
    @emit-args='getNumbers'
    my-msg='message'
   	:dynamic-props='name'
/>

const 

- emit 이벤트 실습

  • 최하단 컴포넌트 ParentGrandChild에서 Parent 컴포넌트의 name 변수 변경 요청하기
<!--ParentGrandChild.vue-->

const emit = defineEmits(['upadateName'])

const updateName = function() {
    emit('updateName')
}

<!--ParentGrandChild.vue-->

<button @click='updateName'>이름 변경</button>
  • 이벤트 수신 후 이름 변경을 요청하는 이벤트 발신
<!--ParentChild.vue-->

<ParentGrandChild
@update-name='updateName'
/>

<!--ParentChild.vue-->

const emit = defineEmits(['updateName'])

const updateName = function() {
    emit('updateName')
}
  • 이벤트 수신 후, 이름 변경 메서드 호출. 해당 변수를 prop으로 받는 모든 곳에서 자동 업데이트
<!--Parent.vue-->

<ParentChild @update-name='updateName'/>

<!--Parent.vue-->

const updateName = function() {
    name.value = 'Bella'
}
profile
새싹 BJY

0개의 댓글