Vue nested component와 props

박경준·2021년 11월 3일
0

vue beginner

목록 보기
11/18

nested component와 props

정적 props를 넘겨줄때엔 v-bind를 넣지 않고 그냥 title로 넘김으로써 string을 전달한다.

// /views/NestedComponent
<template>
  <div>
    <PageTitle title="부모 컴포넌트에서 자식 컴포넌트로 데이터 전달" />
  </div>
</template>
<script>
import PageTitle from '../components/PageTitle';
export default {
  components: {PageTitle}
}
</script>
// /components/PageTitle
<template>
  <h2>{{title}}</h2>
</template>
<script>
export default {
  props: {
    title: {
      type: String,
      default: "페이지 제목입니다."
    }
  }
}
</script>

동적 props

동적 props를 넘겨줄땐 string으로 넘어가지 않도록 하기 위해 :title로 넘겨주고 값으로 "title"을 넣어야 함.

: -> v-bind의 약어

// /components/NestedComponent
<template>
  <div>
    <PageTitle :title="title" />
  </div>
</template>
<script>
import PageTitle from "../components/PageTitle";
export default {
  data() {
    return {
      title: "부모 컴포넌트에서 자식 컴포넌트로 데이터 전달",
    };
  },
  components: { PageTitle },
};
</script>

props 유효성 검사

type, required, default, validator 등의 속성이 있음.

<script>
  export default {
    props: {
      propA: {
        type: Object,
        // Object와 Array type의 props는 default 값을 팩토리 함수로 써야한다.
        default: function() {
          return {message: 'hello'}
        }
      },
      propB: {
        type: Function,
        // Object나 Array와 달리 Function type props는 default 함수 자체가 default 값이다. (팩토리 함수를 의미하는 것이 아님.)
        default: function() {
          return 'default function'
        }
      },
      propC: {
        // 유효성 검사 함수
        // false를 return하면 에러가 뜸.
        validator: function(value) {
          return ['success', 'warning', 'danger'].indexOf(value) !== -1
        }
      },
    }
  }
</script>
profile
빠굥

0개의 댓글