Potato

컴포넌트 구성

 

 

하위 A컴포넌트 ( AChild )에서 버튼을 누르면 B 컴포넌트 ( BChild ) 에게 데이터를 전달해서 출력을 하고 싶다.

 

 

 

 

A 컴포넌트에서 버튼을 클릭했을 때 yes나 no라는 함수를 호출하고 yes나 no함수는 각각 'yes', 'no' 라는 소리를 상위 컴포넌트에 외치게 된다.

<!-- AChild.vue -->

<template>
  <div>
    <h5>{{ msg }}</h5>
    <button @click="yes">O</button>
    <button @click="no">X</button>
  </div>
</template>

<script>
export default {
  name: 'AChild',
  props: {
    msg: String
  },
  methods: {
    yes() {
      this.$emit('yes')
    },
    no() {
      this.$emit('no')
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>

</style>

 

 

Achild에서 yes라는 소리를 들으면 Yes함수를 실행, no라는 소리를 들으면 No라는 함수를 실행하여 mystate에 값을 저장한다.

<!-- App.vue -->

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <div id="box">
      <h2>props, emit을 활용한 데이터 전달</h2>
      <AChild 
      :msg="Amessage"
      @yes="Yes"
      @no="No"
      />
      <BChild 
      :msg="Bmessage"
      :mystate="mystate"
      />
    </div>
  </div>
</template>

<script>
import AChild from './components/AChild'
import BChild from './components/BChild'

export default {
  name: 'App',
  components: {
    AChild,
    BChild,
  },
  data() {
    return {
      Amessage : "Props를 통해 A컴포넌트로 보낸 메세지",
      Bmessage : "Props를 통해 B컴포넌트로 보낸 메세지",
      mystate : '입력 없음'
    }
  },
  methods: {
    Yes() {
      console.log('O버튼 요청보냄');
      this.mystate = 'yes'
    },
    No() {
      console.log('X버튼 요청보냄');
      this.mystate = 'no'
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  margin-top: 60px;
}

#box {
  border : 1px solid gray;
}

</style>

 

BChild에서 APP의 mystate를 props를 사용하여 데이터를 가져와서 출력

<!-- BChild.vue -->

<template>
    <div>
      <h5>{{ msg }}</h5>
      <h3>현재 상태: {{ mystate }}</h3>
    </div>
  </template>
  
  <script>
  export default {
    name: 'BChild',
    props: {
      msg: String,
      mystate : String,
    }
  }
  </script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
  <style>
  
  </style>

'WEB > Vue' 카테고리의 다른 글

[Vue3] Vuex 설치하기  (0) 2023.01.25
[Vue3] Vue-router 설치하기  (0) 2023.01.15
[Vue2/Vuex] state 활용 맛보기  (0) 2022.12.29
[Vue2] EventBus를 통해 컴포넌트간 데이터 전달하기  (0) 2022.12.29
[Vue2] Vue Router 사용하기  (0) 2022.11.09

+ Recent posts