반응형
VueJs Propos에 여러 데이터 유형을 추가하는 방법
컴포넌트에 다른 값을 전달할 때 이 오류가 발생하였습니다.
이게 내가 찾은 해결책이야.
props: {
value: [Number, String, Array]
}
파이프가 있는 구문(
Number | String
승인된 답변에 제시된 바와 같이 실제로는 동작하지 않습니다.자세한 솔루션과 예를 다음에 제시하겠습니다.
타입 체크, 프로포트는 불필요
다음 구문을 사용하여 check prop를 입력합니다.
props: {
username: {
type: [ String, Number ]
}
}
다음은 유형 검사를 사용하는 속성의 실제 예입니다.
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('test-component', {
name: 'TestComponent',
props: {
username: {
type: [ String, Number ]
}
},
template: `<div>username: {{ username }}</div>`
});
new Vue({ el: '#app' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="app">
<!-- valid: String -->
<test-component :username="'user 38'"></test-component>
<!-- valid: Number -->
<test-component :username="59"></test-component>
<!-- valid: null is valid, it is not required -->
<test-component :username="null"></test-component>
<!-- valid: missing property is valid, it is not required -->
<test-component></test-component>
<!-- invalid: Array -->
<test-component :username="['test', 456]"></test-component>
</div>
유형 체크, 필수 프로펠러 및 커스텀 검증 도구
다음 구문을 사용하여 사용자 지정 검증기와 함께 필수 속성 check를 입력합니다.
props: {
username: {
type: [ String, Number ],
required: true, // optional
validator: item => item !== '123' // optional
}
}
다음은 커스텀 검증자와 함께 필요한 속성의 라이브 예입니다.
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('test-component', {
name: 'TestComponent',
props: {
username: {
type: [ String, Number ],
required: true,
validator: item => item !== '123'
}
},
template: `<div>username: {{ username }}</div>`
});
new Vue({ el: '#app' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="app">
<!-- valid: String -->
<test-component :username="'user 38'"></test-component>
<!-- valid: Number -->
<test-component :username="59"></test-component>
<!-- invalid: Array -->
<test-component :username="['test', 456]"></test-component>
<!-- invalid: String, but disallowed by custom validator -->
<test-component :username="'123'"></test-component>
<!-- invalid: null property, it is required though -->
<test-component :username="null"></test-component>
<!-- invalid: missing required prop -->
<test-component></test-component>
</div>
문자열 배열로 나열된 일반적인 소품에서 두통이 없는 경우:
props: ['title', 'likes', 'isPublished', 'commentIds', 'author']
모든 소품이 특정 유형의 가치가 되기를 원하는 경우.이 경우 소품을 객체로 나열할 수 있습니다. 여기서 특성 이름과 값에는 소품 이름과 유형이 각각 포함됩니다.
props: {
title: String,
likes: Number,
isPublished: Boolean,
commentIds: Array,
author: Object
}
여러 유형을 사용하는 경우 다음과 같이 하십시오.
props: {
value: [String, Number],
}
다른 사람들이 제안했듯이 vuej에서 소품을 정의하는 방법은 두 가지가 있습니다.
첫 번째 거
//No need to define the type with this one
props: ['myVariable', 'foo', 'something']
두 번째 거
//With this one you can define what type the prop is and other different useful things!
props: {
myVariable: String, //You can define the type like this
anyOfTheFollowing: String/Object/Array, //You can also define multiple possible types
'kebab-case-like': Function, //Since vuejs is still javascript and the property 'props' is actually an object, you can define your props like this for kebab-case. You can also just use camelCase and use the kebab-case version in your template and it will still recognize it
customOne: MyCustomType, //You can in theory use classes you've defined aswell
foo: { //This is another way of defining props. Like an object
type: Number,
default: 1, //This is why this is mostly used, so you can easily define a default value for your prop in case it isn't defined
},
andAnotherOne: {
type: Array,
default: () => [], //With Arrays, Objects and Functions you have to return defaults like this since you need to return a new reference to it for it to be used
},
requiredOne: {
type: Object,
required: true //Another use for this. When it is marked as required and it isn't defined you'll get an error in the console telling you about it
}
}
IMO 저는 두 번째 버전이 훨씬 더 많이 열려 있고, 특히 디폴트 속성을 가장 좋아합니다.
언급URL : https://stackoverflow.com/questions/53608244/how-to-add-multiple-data-types-for-vuejs-props
반응형
'programing' 카테고리의 다른 글
Java: 쉼표로 구분된 문자열을 분할하지만 따옴표로 둘러싸인 쉼표는 무시합니다. (0) | 2022.07.14 |
---|---|
Java 8 스트림 역순서 (0) | 2022.07.14 |
JavaBean이란 정확히 무엇입니까? (0) | 2022.07.14 |
브라우저 닫기 시에만 함수를 호출하는 방법 (0) | 2022.07.14 |
Maven이 의존관계를 타겟/립에 복사하도록 하다 (0) | 2022.07.14 |