본문 바로가기
FrontEnd/Vue 2

[Vue.js] 같은 레벨의 컴포넌트 간의 데이터 통신 (React의 State 끌어올리기)

by Chaedie 2022. 9. 15.
728x90

Vue.js에선 같은 레벨의 컴포넌트 간의 데이터 통신을 어떻게 할까?

  • React의 State끌어올리기를 Vue.js에선 어떻게 구현할까?
  • Vue.js의 컴포넌트간 데이터 통신 방법은 아래로 Props, 위로 Event이다.
  • 이 둘을 이용해서 Event로 올리고, Props로 다시 내리면 같은 레벨 컴포넌트간 통신이 가능하다.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <div id="app">
      {{str}}
      <app-header v-bind:propsdata="number"></app-header>
      <app-content v-on:pass="deliverNumber"></app-content>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
      let appHeader = {
        template: `<div>header
          {{propsdata}}
          </div>`,
        props: ['propsdata'],
      };

      let appContent = {
        template: `
        <div>content
          <button v-on:click="passNumber">pass</button>
        </div>`,
        methods: {
          passNumber: function () {
            this.$emit('pass', 10);
          },
        },
      };

      new Vue({
        el: '#app',
        data: {
          str: 'hi',
          number: 0,
        },
        components: {
          'app-header': appHeader,
          'app-content': appContent,
        },
        methods: {
          deliverNumber: function (value) {
            this.number = value;
          },
        },
      });
    </script>
  </body>
</html>

댓글