'Default values of a prop of type object in vue are not being used
I'm not sure why the default values of a prop, in object format, in vue are not being accepted but when I pass in the props dynamically the values appear fine.
I have a component, component1, it has:
<label :style="setTextStyles"></label>
props: {
textStyles: {
type: Object,
default: () => ({
'textColor': 'white',
'uppercase': 'uppercase',
'fontWeight': 'bold',
})
}
},
computed:{
setTextStyles() {
return {
'font-weight': this.textStyles.fontWeight,
'text-transform': this.textStyles.uppercase,
'--color': this.textStyles.textColor
}
}
I have a second component that uses component 1:
<component1 :textStyles="{'textColor':'red', 'uppercase':'None','fontWeight':'bold'}"/>
Which ever prop I specify, ie textColor, or upprecase or fontWeight, I see the expected result. However the default values don't seem to show up if I don't specify it. For example, the fontWeight is not bold by default even though it's set as the default font weight. This is the same with textColor.
Below does not give me a bold font:
<component1 :textStyles="{'textColor':'red', 'uppercase':'None'}"/>
Below does not give me a white text color:
<component1 :textStyles="{'uppercase':'None','fontWeight':'bold'}"/>
I'm not sure why the default values are not appearing
Solution 1:[1]
Do not expect vue props to act like function arguments in javascript. Instead you can have the default values in a separate variable inside the component and use Object.assign() to build the final desired object.
For example:
const defaultStyles = {
'textColor': 'white',
'uppercase': 'uppercase',
'fontWeight': 'bold',
}
export default {
props : {
textStyles : {
default : {},
type : Object
}
},
data(){
return {
finalStyles : Object.assign({}, defaultStyles, textStyles)
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ahmad Mobaraki |
