다른 소품 검증기에서 소품 값에 액세스
다른 소품 검증기의 소품 값에 액세스하고 싶다.
props: {
type: {
type: String,
default: "standard"
},
size: {
type: String,
default: "normal",
validator(value) {
// below I want to access the props `type` from above.
return (this.type !== "caution" || this.type !== "primary") && value !== "mega"
}
}
}
하지만 난 점점TypeError: Cannot read property 'type' of undefined
.감 잡히는 게 없어요?
그this
소품에서 가변적인validator
는 Vue 인스턴스를 참조하지 않습니다.그리고 유감스럽게도 프로포트의 가치에서 다른 프로포트의 가치를 참조할 수 있는 실질적인 방법은 없습니다.validator
기능.
Vue 인스턴스의 Watcher를 설정할 수 있습니다.$props
오브젝트, 설정immediate
할 수 있는 선택권true
컴포넌트가 생성되면 워처가 기동합니다.그 감시자는 검증 논리를 작동시킬 수 있어요this
Vue 인스턴스에 대한 참조입니다.
다음은 간단한 예입니다.
Vue.config.productionTip = false;
Vue.config.devtools = false;
Vue.component('child', {
template: '<div></div>',
props: {
type: {
type: String,
default: "standard"
},
size: {
type: String,
default: "normal"
}
},
methods: {
validateProps() {
if ((this.type === "caution" || this.type === "primary") && this.size === "mega") {
console.error('Invalid props');
}
}
},
watch: {
$props: {
immediate: true,
handler() {
this.validateProps();
}
}
}
});
new Vue({
el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<child type="caution" size="mega"></child>
</div>
또 다른 옵션은 다음과 같이 개체를 전달하는 것입니다.type
그리고.size
하나의 소품으로 사용할 수 있습니다.그렇게 하면validator
두 가지 가치를 모두 참조할 수 있습니다.
Vue.config.productionTip = false;
Vue.config.devtools = false;
Vue.component('child', {
template: '<div></div>',
props: {
config: {
type: Object,
default: () => ({ type: "standard", size: "normal" }),
validator({ type, size }) {
return !((type === "caution" || type === "primary") && size === "mega");
}
}
}
});
new Vue({
el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<child :config="{ type: 'caution', size: 'mega'}"></child>
</div>
(또한 주의: 검증 로직이 올바르지 않을 수 있습니다.기재된 바와 같이 괄호 안의 문장은 항상 다음과 같이 평가됩니다.true
이 논리를 예시로 업데이트했습니다.
검증이 1회만 필요한 경우 단순히 mounted() 핸들러로 검증합니다.이 경우 재스트 테스트에 실패하고 브라우저에 오류가 기록됩니다.
props: {
type: {
type: String,
default: "standard"
},
size: {
type: String,
default: "normal"
}
},
mounted() {
if ((this.type === "caution" || this.type === "primary") && this.size === "mega") {
console.error('Invalid props');
}
}
불가능합니다.VUE 프로젝트에는 몇 가지 제안이 있었지만 모두 거부되었습니다.
https://github.com/vuejs/vue/issues/3495
https://github.com/vuejs/vue/issues/6787
https://github.com/vuejs/vue/issues/9925
이러한 경우의 간단한 방법은 계산된 속성을 사용하거나 속성을 검증하는 것입니다.created
이 경우 모든 속성을 사용할 수 있습니다.
언급URL : https://stackoverflow.com/questions/56904327/access-props-value-in-another-props-validator
'programing' 카테고리의 다른 글
int의 사이즈는 올바른데 int의 사이즈는 잘못된 이유는 무엇입니까? (0) | 2022.06.29 |
---|---|
Vuetify 아이콘이 올바르게 표시되지 않음: "$vuetify.icons"로 표시됩니다.." (0) | 2022.06.28 |
휘발성이 멀티스레드 C 또는 C++ 프로그래밍에서 유용하다고 생각되지 않는 이유는 무엇입니까? (0) | 2022.06.28 |
Vue.js에서의 디버깅 (0) | 2022.06.28 |
Vue Devtool 확장 힌트 사용 안 함 (0) | 2022.06.28 |