When I have a Vue.js component it could look like:
import Icon from './Components/Icon.vue'
export default {
props: {
data: {type: Object}
},
data() {
return {
label: this.data.label || '',
icon: this.data.icon || '',
placeholder: this.data.placeholder || '',
value: this.data.value || '',
disabled: this.data.disabled || false,
readOnly: this.data.readOnly || false,
options: this.data.options || []
}
},
components: {
Icon: Icon
}
}
How does the namespace work in Vue? Is both props keys, data return object keys, and all components object keys will be added to the this
instance? Is there not a risk for bugs/over-writing stuff?
So if I override this.data
can I still read the original value I received in the props
?
What is the community practise for setting "default" values in the data
state object comming from props
so we can both have a dynamic state
object, and keep the props
there in case we need it?
And related: if pass props
with v-bind
should I add them to watch
internally on my component? or make all my dynamic values a computed version taking into consideration props
everytime it is called?
Thanks for feedback.
Vue will warn you if you have a conflicting property name. For example, if you had this in your component:
props: ['foo'],
data() {
return {
foo: 'bar',
}
},
You would get this warning:
[Vue warn]: The data property "foo" is already declared as a prop. Use prop default value instead.
And (as the warning alludes to), if you want to set a default value of a prop, you should do it in the definition of the prop like so:
props: {
foo: { type: String, default: 'bar' }
},
In your example, you are passing a prop named data
and using it to set the data properties of the Vue component. So the component will have access to this.label
, this.icon
, etc., and it will also have access to this.data.label
, this.data.icon
, etc.
This isn't overwriting anything because your prop named data
is referencing a different object than your component's data properties. Bu, you probably don't ever want to name a property data
, because you can see how it might get confusing.
It looks like you are, in general, trying to pass an object with property values to a component instead of having to set each one individually. You can do this with v-bind
like so:
// assuming that var settings = { foo: 1, bar: 2 }
<child-component v-bind="settings"></child-component>
Child component:
props: {
foo: { type: Number, default: 0 },
bar: { type: Number, default: 0 },
// you can still set defaults for props not passed in the object
baz: { type: Number, default: 0 },
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.