컴포넌트 교환
페이지 구성 시, 공통적으로 사용되는 컴포넌트를 부모가 관리하고 상호 간 교류하는 방법을 기술.
순서: 컴포넌트 파일 생성→ 부모 컴포넌트에서 등록→ 실행
- src/components에 컴포넌트 파일 생성
- src/view폴더에 부모 컴포넌트 파일 생성
- example
- components 디렉토리에 "PageTitle" 이름의 파일 생성
- 태그 생성, import, 컴포넌트 등록
- example
1
2
3
4
5
6
7
8
9
10
11
|
<template>
<div>
<PageTitle /> //html에서는 import한 컴포넌트 이름을 이용해 태그 생성
</div>
</template>
<script>
import PageTitle from '../components/PageTitle'; // import
export default {
components:{PageTitle} //현재 파일에서 사용할 컴포넌트 등록
}
</script>
|
cs |
- 부모→ 자식 컴포넌트
- 데이터 전달 format
1
2
3
4
5
6
7
8
9
10
11
|
<template>
<h2> {{title}}</h2> //아래에서 전달받은 값 출력
</template>
export default {
props:{
title:{
type:String,
default:"페이지 제목"
}
}
}
|
cs |
- props인자를 사용하여 부모로부터 전달받을 데이터를 받음
- default는 부모로부터 데이터를 전달받지 않았을 때의 기본 값
1
2
3
4
5
6
7
8
9
10
11
12
|
<template>
<div>
<PageTitle title="데이터 전달"/>
</div>
</template>
<script>
import PageTitle from '../components/PageTitle';
export default {
components:{PageTitle}
}
</script>
|
cs |
또한 부모 파일의 prop에 v-bind를 이용하여 동적인 값을 전달할 수 있음.
목록: 숫자형, 논리형, 배열, 객체, 속성 등
2. 부모→ 자식 컴포넌트(이벤트 호출)
- format
1
2
3
4
5
6
7
8
9
10
11
12
|
<template>
<button type="button" @click="childFunc" ref="btn">click</button>
</template>
<script>
export default {
methods:{
childFunc(){
console.log('이벤트 작성문');
}
}
}
</script>
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
|
<template>
<childComponent @send-message="sendMessage" ref="childComponent" />
</template>
<script>
import childComponent from './childComponent';
export default {
components: {childComponent},
mounted() {
this.$refs.childComponent.$refs.btn.click();
}
}
</script>
|
cs |
- 자식 컴포넌트 객체에 "ref"속성으로 접근할 수 있음. (html의 id와 유사)
3. 부모→ 자식 컴포넌트(데이터 변경)
1
2
3
4
5
6
7
8
9
10
11
12
|
<template>
<h1>{{msg}}</h1>
</template>
<script>
export default {
data() {
return {
msg: ''
};
}
}
</script>
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<template>
<childComponent @send-message="sendMessage" ref="childComponent" />
<button type="button" @click="changeChildData">Change Child Data</button>
</template>
<script>
import childComponent from './childComponent';
export default {
components: {childComponent},
methods: {
changeChildData() {
this.$refs.childComponent.msg = "부모 컴포넌트가 변경한 데이터";
}
}
}
</script>
|
cs |
2. 자식 컴포넌트→ 부모
- 이벤트/데이터 전달
- format
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<template>
<div></div>
</template>
<script>
export default {
data() {
return {
msg: '자식 컴포넌트로부터 보내는 메시지'
};
},
mounted() {
this.$emit('send-message', this.msg)
}
}
</script>
|
cs |
- 자식이 부모로 데이터를 전달할 때는 emit인자를 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<template>
<childComponent @send-message="sendMessage" />
</template>
<script>
import childComponent from './childComponent';
export default {
components: {childComponent},
methods: {
sendMessage(data) {
console.log(data);
}
}
}
</script>
|
cs |
Provide/Inject
위처럼 계층 구조가 복잡한 경우 부모↔ 자식 간 컴포넌트 교환이 어렵기 때문에 provide/inject옵션을 지원하여 이벤트/데이터 전달을 한번에 처리할 수 있음.
- 부모가 값을 전달할 때 provide함수 이용
- 자식이 값을 전달 받을 때는 inject인자 사용
- 사용이 권장되진 않음.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
<template>
<div>
<ProvideInjectChild />
</div>
</template>
<script>
import ProvideInjectChild from './ProvideInjectChild';
export default {
components: {ProvideInjectChild},
data() {
return {
items: ['A','B']
};
},
provide() {
return {
itemLength: this.items.length
};
}
}
</script>
|
cs |
- Provide 옵션 사용 말고는 일반적인 컴포넌트 교환 방식과 동일.
- 위 example에서는 자식 컴포넌트로 전달하려는 데이터를 provide에 정의.(배열 길이)
1
2
3
4
5
6
7
8
9
10
11
|
<template>
<div></div>
</template>
<script>
export default {
inject: ['itemLength'],
mounted() {
console.log(this.itemLength);
}
}
</script>
|
cs |
- 부모 컴포넌트로부터 전달받을 데이터와 동일한 이름으로 inject에 '문자열 배열'로 정의.
Vuex
Vue js 애플리케이션을 위한 상태관리 패턴+라이브러리로, 데이터를 store에 저장하고 프로젝트 전체에서 사용하는 등, 모든 컴포넌트에 대한 중앙 집중식 저장소 역할을 함.
즉, 단일 객체에 변수를 선언하고 모든 컴포넌트에서 사용할 수 있음
→ props/emit 등 복잡한 컴포넌트 관리를 대체해줌.
설치: npm install vuex@next --save
Store: 애플리케이션 상태를 저장하고 있는 컨테이너(전역 저장소)
속성
- State: 프로젝트 전체에서 공통으로 사용할 변수를 정의하는 곳(한번만 정의하여 모든곳에서 사용
→ 변경 여부를 감시하는 computed와 함께 자주 사용됨.
- Getters: 어떤 값들을 저장소의 state에 관리할 때, getters를 정의하여 쉽게 가져올 수 있음.
- Mutations: 기본적으로 state에 정의된 변수를 변경할 수 없고, mutations을 이용해서 변경해야함.
- Actions: mutations과 유사하지만 actions함수 안에서는 여러개의 mutations을 실행 시킬 수 있고 서버로부터 데이터 fetch등 비동기 처리 로직을 관리할 수 있게 해줌.
Vuex 사이클
Component에서 비동기 호출(Actions) → 데이터 조작(Mutations)→ 데이터 저장(state)
사용 예: 회원가입 시 사용자 인증, 토큰 처리 등과 관련된 정보들을 서버뿐만 아니라 vue에서(front-end) 관리하여 이벤트 처리를 하고싶을 때