관리 메뉴

샐님은 개발중

#7.vue기초 형제 컴포넌트로 데이터 전달(event bus) 본문

vue/vue기초

#7.vue기초 형제 컴포넌트로 데이터 전달(event bus)

샐님 2021. 9. 1. 03:58
728x90
반응형

패키지 구조

 

*1번째 방법 : 자식 -> 부모 -> 자식

 

1. UserEdit.vue - 전달하려는 컴포넌트

<script>
export default {
......
 methods:{
   editInfo(){
     console.log(this.user);
     //1번째, 부모로 전달후 자식 데이터가 변경되는 형식으로 형제 컴포넌트에도 데이터 전달.
     this.$emit('child',this.user) //자식 컴포넌트가 부모컴포넌트에게 데이터전달을 하기 위한 것. 
    // 함수로 표현하면: child(this.user) 으로 표현가능.
 
 }
}
</script>

2.  User.vue - 부모 컴포넌트 (자식이 보낸 데이터 받기)

   <UserEdit
          :name="name"
          :address="address"
          :phone="phone"
          :hasDog="hasDog"
          @child="parents"><!--child라는 신호가 오면 parents를 실행해줘! 라는 의미 -->
          </UserEdit>
   .
   .
   .
   
<script>
import UserDetail from "./UserDetail.vue"
import UserEdit from "./UserEdit.vue"

export default {
.
.

  methods:{
  .
  .
  
    parents(user){ 
    // 자식이보낸 데이터 객체user를 자신의 데이터에 셋팅 하므로서 자식(userDetail) 데이터도 함께 변경됨.
    // user ={name,address,phone,hasDog}
      this.name = user.name
      this.address = user.address
      this.phone = user.phone
      this.hasDog = user.hasDog
   
    }
  }
}
</script>

* 2번째 방법: eventBus 이용

1.  main.js - eventBus 추가, 형제 컴포넌트 간의 데이터 전달시 필요.

import '@babel/polyfill'
import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'

Vue.config.productionTip = false

export const eventBus = new Vue() 
// 이벤트 버스라는 상수를 내보내는데 이것은 새로운 뷰 인스턴스를 생성해 내보내고 있음.


new Vue({
  render: h => h(App)
}).$mount('#app')

2. UserEdit.vue -eventBus를 이용해 데이터 전달

<script>
import {eventBus} from "../main" // 객체형태로 넣어줌 main.js에서 불러옴
export default {
 props:['name','address','phone','hasDog'],

 data: () => ({
   user:{} // 1.새로운 객체에 props로 받은 값들 넣
  }),
  created(){ //2.새롭게 할당함 3. v.model 앞에 user.~으로 변경
    this.user.name = this.name 
    this.user.address = this.address
    this.user.phone = this.phone
    this.user.hasDog = this.hasDog
    
  },

 methods:{
   editInfo(){
   eventBus.$emit("userWasEdited",new Date())
    //userWasEdited라는 신호가 eventBus로 전달이됨. new Date와 함께.
    //$eit~는 자식이 부모에게 데이터 전달시 사용함. 이런 관점에서 eventBus라는 인스턴스가 '부모'역할
    //을 한다고 할수 있음. 즉, 보내는 데이터를 eventBus가 받는 다고 할수 있음. (형제컴포넌트를 연결하기 위해 가상의 부모 역할을 한다고 추론가능.)

 }
}
</script>

3. userDetail.vue - 형제에게 데이터 받기

<script>
import {eventBus} from "../main"

export default {

 data: () => ({
   editedDate: null, 
  }),
props:['name','address','phone','hasDog'],

 methods:{
 created(){
   eventBus.$on('userWasEdited',date =>{ //userWasEdited 신호로 보낸 date를 editedDate에 넣어줘!
      //vue에서 콜백함수를 쓸때는 에로우 표기법을 사용해서 this가 그대로 사용됨.
    this.editedDate = date;
  })
 }
}
</script>

* 3번째 방법: main.js 의 eventbus 에 함수 추가

 

1.main.js - 함수생성가능

export const eventBus = new Vue({
  methods:{
    userWasEdited(date){
      this.$emit('userWasEdited',date)
    }

  }
})

2.UserEdit -정의된 함수 사용

 methods:{
   editInfo(){
  
    eventBus.userWasEdited(new Date()); //main.js에서 eventBut에 만든 함수를 호출해서 사용할 수 도 있다.
   }
 }
728x90
반응형

'vue > vue기초' 카테고리의 다른 글

Vuex #3 MUTATIONS 사용  (0) 2021.09.12
Vuex #1 state  (0) 2021.09.12
#6.vue기초 자식 ->부모 컴포넌트로 데이터 전달(. $emit)  (0) 2021.09.01
#5.vue기초 props 활용2  (0) 2021.09.01
#4.vue기초 props 활용  (0) 2021.09.01