How do you go on passing objects as props on vue? I would imagine this would be a simple task but apparently not.
I have the following code on a .vue
file:
<template>
<div id="scatter"></div>
</template>
<script>
export default {
props: {
data: {
type: Object,
default: () => ({}),
},
},
mounted() {
console.log(this.data);
},
};
</script>
On html I try to pass the data
props as follows :
<component :data="{x:1}"></component>
When I try log it into the console the result is only an empty observer object.
To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.
You can pass strings, arrays, numbers, and objects as props. But can you pass a function as a prop? While you can pass a function as a prop, this is almost always a bad idea. Instead, there is probably a feature of Vue that is designed exactly to solve your problem.
Vue does not take a copy when you pass objects via props. If you pass an object via a prop then both components will be seeing the same object. As it's the same object, any property changes made by the child will also impact the other parent.
I believe the problem is somewhere else in your code as passing an object as a prop is as simple as you imagine:
// register the component Vue.component('component', { props: { data: { type: Object } }, template: '<div>Data: {{data}}</div>', mounted: function () { console.log(this.data) } }) new Vue({ el: '#example' })
HTML:
<div id="example"> <component :data="{x:1}"></component> </div>
Here's a fiddle showing it in action: https://jsfiddle.net/tk9omyae/
Edit: After my initial answer and creating a JsFiddle, I am not sure why the behavior you described is happening. It works when narrowed down to the use case:
<script>
export default {
props: {
ok: {
type: Object,
default: () => ({}),
},
data: {
type: Object,
default: () => ({})
}
}
},
mounted () {
console.log(this.data) // {x:1}
console.log(this.ok) // {x:1}
}
}
</script>
And the HTML:
<component :ok="{x:1}" :data="{x:1}"></component>
Here is a JsFiddle that demonstrates the behavior: https://jsfiddle.net/mqkpocjh/
v-bind="yourObject"
Should do on
<my-component v-bind="yourObject"><my-component>
Not sure about <component></component>
. Still digging into Vue. Try and let us know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With