티스토리 뷰
컴포넌트 구조
- App.vue > Container.vue > FilterBox.vue
mitt 라이브러리를 사용해서 FilerBox 컴포넌트에서 App 컴포넌트로 데이터 전송하기
- 설치
npm install mitt
- 세팅
// main.js
...
import mitt from 'mitt';
let emitter = mitt();
let app = createApp(App);
app.config.globalProperties.emitter = emitter;
// app.config.globalProperties: 글로벌한 변수보관함 - 보관함에 { emitter: emitter } 추가
app.mount('#app');
mitt로 데이터 전송하는 방법
- 데이터 전송할 컴포넌트에서 this.emitter.emit()
- 데이터 수신할 컴포넌트에서 this.emitter.on()
- 데이터 보내기
<!-- 데이터 보낼 컴포넌트 -->
<template>
<button @click="fire">버튼</button>
</template>
<script>
export default {
name: 'Filter-box',
methods: {
fire() {
// this.emitter.emit('작명', '데이터'); // 보낼 데이터 작성
this.emitter.emit('selectedFilter', this.filter);
},
},
};
</script>
- 데이터 받기
<!-- 데이터 받는 컴포넌트 -->
<template>
<!-- 필터선택페이지 -->
<div v-if="step == 1">
<div :class="`upload-image ${selectedFilter}`" :style="{ backgroundImage: `url(${image})` }"></div>
...
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
postData: postData,
moreCount: 0,
step: 0,
image: '',
writePost: '',
selectedFilter: '', // <- 추가
};
},
methods: {
...
publish() {
let myPost = {
name: 'Kim Hyun',
userImage: 'https://picsum.photos/100?random=3',
postImage: this.image,
likes: 36,
date: 'May 15',
liked: false,
content: this.writePost,
filter: this.selectedFilter, //<-emitt으로 받아온 데이터 갱신
};
this.postData.unshift(myPost);
this.step = 0;
},
},
mounted() {
// this.emitter.on('작명', () => {
// '실행할 코드';
// });
this.emitter.on('selectedFilter', (filter) => {
this.selectedFilter = filter;
});
},
...
};
</script>
❗ mitt는 많이 사용하면 관리가 힘들어짐 -> Vuex 사용하기
'Library | Framework > Vue JS' 카테고리의 다른 글
| [Vue] 20. PWA (0) | 2023.08.07 |
|---|---|
| [Vue.js] 19. Vuex (0) | 2023.08.07 |
| [Vue.js] 17. slot (0) | 2023.08.07 |
| [Vue.js] 16. 서버없이 이미지 업로드 (0) | 2023.08.06 |
| [Vue.js] 15. Ajax (0) | 2023.08.06 |
댓글
