props: {
rules: {
type: Array,
required: false,
default: () => [
(file) => !file
|| file.size < 10000000
|| this.getJsonDataByLocale.less_than_10mb_message,
(file) => !file
|| ACCEPTED_FILE_TYPES.includes(file.type)
|| this.getJsonDataByLocale.wrong_file_message,
],
}
}
This is generic component. I'm trying to set rules default to a computed property. 'this.getJsonDataByLocale' is a getter computed property.
It seems to be like as Vue life cycle renders props earlier than the computed property so it doesn't know how to fetch the data from the computed property.
I really need to use 'this.getJsonDataByLocale', as this error msg needs to be a dynamic value.
Anyone can give me some advices?
CodePudding user response:
As Vue's official doc says,
Note that props are validated before a component instance is created, so instance properties (e.g. data, computed, etc.) will not be available inside default or validator functions. link
So I think we can't access computed property in props
CodePudding user response:
As others have pointed out, you simply cannot use computed values in your props. But couldn't you just do it the other way around and use the prop in a computed? Something like this:
props: {
rules: {
type: Array,
required: false,
default: () => []
}
},
computed: {
errorMsg() {
if (!this.rules.length) { // No rules prop data: use default
return [
(file) => !file
|| file.size < 10000000
|| this.getJsonDataByLocale.less_than_10mb_message,
(file) => !file
|| ACCEPTED_FILE_TYPES.includes(file.type)
|| this.getJsonDataByLocale.wrong_file_message,
]
}
// We do have rules prop data: use that
return this.rules;
}
}