1) 문자열 배열 선언
// BlogPost.vue
export default {
props: ['title'],
setup(props) {
console.log(props.title)
}
}
2) 객체문법 선언
export default {
props: {
title: String,
likes: Number
},
setup(props) {
console.log(props.title)
console.log(props.likes)
}
}
{
// Basic type check
// (`null` and `undefined` values will allow any type)
propA: Number,
// Multiple possible types
propB: [String, Number],
// Required string
propC: {
type: String,
required: true
},
// Number with a default value
propD: {
type: Number,
default: 100
},
// Object with a default value
propE: {
type: Object,
// Object or array defaults must be returned from
// a factory function
default() {
return { message: 'hello' }
}
},
// Custom validator function
propF: {
validator(value) {
// The value must match one of these strings
return ['success', 'warning', 'danger'].includes(value)
}
},
// Function with a default value
propG: {
type: Function,
// Unlike object or array default, this is not a factory function - this is a function to serve as a default value
default() {
return 'Default function'
}
}
}
3) 단방향 데이터 흐름
1. prop은 초기 값을 전달하는 데 사용됩니다. 자식 컴포넌트에서 속성 값을 로컬 데이터 속성으로 사용 하고자할 때 입니다. 이 경우 prop을 초기 값으로 사용하는 로컬 변수를 선언하는 것이 가장 좋습니다.
export default {
props: ['initialWidth', 'initialHeight'],
setup(props) {
// width는 props.initialWidth 값으로 초기화 됩니다.
// 향후 props 업데이트의 연결이 끊어집니다.
const width = ref(props.initialWidth)
const height = ref(props.initialHeight)
return {
width,
height
}
}
}
2. prop의 값의 변환이 필요할 때 입니다. 이 경우 computed를 사용하면 좋습니다. 그리고 상위 속성의 변경을 유지할 수 있습니다.
export default {
props: ['size'],
setup(props) {
// 향후 props 업데이트의 연결이 유지됩니다.끊어집니다.
const rectangleSize = computed(() => props.size.trim().toUpperCase());
return {
rectangleSize
}
}
}
'개발이 좋아서 > Vue가 좋아서' 카테고리의 다른 글
15장 Non-Prop 속성 (fallthrough 속성) (0) | 2023.09.14 |
---|---|
14장 Events (0) | 2023.09.14 |
12장 Watch, WatchEffect (0) | 2023.09.14 |
11장 양방향 바인딩(v-model) (0) | 2023.09.14 |
10장 이벤트 처리 (0) | 2023.09.13 |