I'm new to VueJS, so I've been following their official guide.
I'm able to trigger the first 5 properties validator, but I can't seem to be able to trigger the last example (custom validation function).
my JS file:
Vue.component('propValidation', {
props: {
// basic type check (`null` means accept any type)
propA: Number,
// multiple possible types
propB: String,
// a required string
propC: {
type: String,
required: true
},
// a number with default value
propD: {
type: Number,
default: 100
},
// object/array defaults should be returned from a
// factory function
propE: {
type: Object,
default: function () {
return { message: 'hello' }
}
},
// custom validator function
propF: {
type: Number,
validator: function (value) {
console.log("inside validator: " + value);
return value > 10;
}
}
},
template:"<div>" +
"<p>PropA (Number): {{propA}}</p>" +
"<p>PropB ([String, Number]): {{propB}}</p>" +
"<p>PropC (Require String): {{propC}}</p>" +
"<p>PropD (Default Number): {{propD}}</p>" +
"<p>PropE (Default Object/Array): {{propE}}</p>" +
"<p>PropF (Custom Validator): {{propF.validator()}}</p>" +
"</div>"
});
new Vue({
el:"#example"
});
and the HTML file:
<div id="example">
<prop-validation :prop-a="200" prop-b="string" prop-c="Require String" :prop-e="{not:'wee'}" :prop-f="5"></prop-validation>
</div>
and finally the result:
PropA (Number): 200
PropB ([String, Number]): string
PropC (Require String): Require String
PropD (Default Number): 100
PropE (Default Object/Array): { "not": "wee" }
PropF (Custom Validator):
with the warning:
[Vue warn]: Invalid prop: custom validator check failed for prop "propF".
(found in component <propValidation>)
Thanks in advance
edit: Now that I think about it, Is it suppose to return 'true' as the output or does it just give a warning that it isn't correct? I might've been looking at this differently and expecting the return value to be either true/false.
You might want to checkout vue-properties:
import {biggerThan} from 'vue-properties';
export default {
props: {
canDrink: {
type: Integer,
validator: biggerThan(18)
},
}
}
According to the docs:
It is possible for a component to specify requirements for the props it is receiving. If a requirement is not met, Vue will emit warnings. This is especially useful when you are authoring a component that is intended to be used by others.
What they're saying here is that the validators you specify, should be met at all times for this property to properly work. If not, they'll emit a warning, just like the one you're experiencing.
When you define the validator like this, you're saying that all input for this specific validator should be larger than 10.
validator: function (value) {
console.log("inside validator: " + value);
return value > 10;
}
Then when you bind the number 5 as value to this specific property, the validator returns false and emits the warning.
来源:https://stackoverflow.com/questions/41578945/vuejs-custom-props-validation-function