본문 바로가기

programming/Vue

[Vue.js] #2 부모 - 자식 관계 컴포넌트 구현

부모 - 자식 관계의 컴포넌트 구현

 

1. 자식 요소를 태그로 사용 가능

v-bind -> : 으로 축약표현

왜? bind를 하면 Vue에서 정의한 데이터를 찾음 -> count 라는 데이터(Parent에서 정의) 를 찾아서 Child에게 props로 넘김

<body>
    <div id="app">
      <Child :something="count" />
    </div>
</body>

2. 자식 요소 생성 (순서 중요 : 자식먼저 작성)

<script src="https://unpkg.com/vue"></script>
  <script>
    const Child = {
      props: { somthing: Number },
      data() {
        return {
          color: 'red',
        };
      },
      methods: {
        changeColor: function () {
          if (this.color === 'red') return (this.color = 'blue');
          this.color = 'red';
        },
      },
      template: `
        <h1 v-bind:style="{ color : color }"> Child Componont </h1>
        <h2> {{ something }} </h2>
        <button @click="changeColor">Switch Color</button>
        `,
    };

3. 부모 요소 생성

const Parent = {
      data() {
        return {
          count: 0,
        };
      },
      components: {
        Child,
      },
    };

    Vue.createApp(Parent).mount('#app');
  </script>

 

 

전체 예시 코드

<!DOCTYPE html>
<html>
  <head>
    <title>Example 03</title>
  </head>
  <body>
    <div id="app">
      <Child :something="test" />
    </div>
  </body>

  <script src="https://unpkg.com/vue"></script>
  <script>
    const Child = {
      props: { somthing: Number },
      data() {
        return {
          color: 'red',
        };
      },
      methods: {
        changeColor: function () {
          if (this.color === 'red') return (this.color = 'blue');
          this.color = 'red';
        },
      },
      template: `
        <h1 v-bind:style="{ color : color }"> Child Componont </h1>
        <h2> {{ something }} </h2>
        <button @click="changeColor">Switch Color</button>
        `,
    };

    const Parent = {
      data() {
        return {
          count: 0,
        };
      },
      components: {
        Child,
      },
    };

    Vue.createApp(Parent).mount('#app');
  </script>
</html>

 

실행 결과