Last active
November 20, 2017 15:36
-
-
Save danielsdeboer/c0388b7df11618006c35610a03cd2037 to your computer and use it in GitHub Desktop.
Importing props in VueJs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Instead of doing this in lots of components: | |
export default { | |
props: { | |
colorClass: { | |
type: String, | |
required: true, | |
default: 'blue', | |
validator: value => ['red', 'blue'].includes(value) | |
} | |
} | |
// ...etc | |
} | |
// Since the prop definition is just an object you can extract that to prop definition file: | |
export const colorClass = { | |
type: String, | |
required: true, | |
default: 'blue', | |
validator: value => ['red', 'blue'].includes(value) | |
} | |
// But let's say you have different default requirements for different components... | |
// You could create a factory function: | |
export const colorClass = (color = 'blue') => { | |
return { | |
type: String, | |
required: true, | |
default: color, | |
validator: value => ['red', 'blue'].includes(value) | |
} | |
} | |
// Then in your component you can import the prop object: | |
import { colorClass } from 'Props' | |
export default { | |
props: { | |
colorClass, | |
} | |
} | |
// Or import the factory function, creating a prop that defaults to red: | |
import { colorClass } from 'Props' | |
export default { | |
props: { | |
colorClass: colorClass('red'), | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment