Pass object as prop on Vue
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.
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.