[英]Pass object as prop on Vue
How do you go on passing objects as props on vue?你如何继续在 vue 上将对象作为道具传递? I would imagine this would be a simple task but apparently not.
我想这将是一项简单的任务,但显然不是。
I have the following code on a .vue file:我在 .vue 文件中有以下代码:
` `
<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 :在 html 上,我尝试按如下方式传递
data
道具:
<component :data="{x:1}"></component>
When I try lo 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: HTML:
<div id="example">
<component :data="{x:1}"></component>
</div>
Here's a fiddle showing it in action: https://jsfiddle.net/tk9omyae/这是一个显示它在行动中的小提琴: https : //jsfiddle.net/tk9omyae/
Edit: After my initial answer and creating a JsFiddle, I am not sure why the behavior you described is happening.编辑:在我最初的回答并创建一个 JsFiddle 之后,我不确定为什么你描述的行为正在发生。 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:和 HTML:
<component :ok="{x:1}" :data="{x:1}"></component>
Here is a JsFiddle that demonstrates the behavior: https://jsfiddle.net/mqkpocjh/这是一个演示行为的 JsFiddle: https ://jsfiddle.net/mqkpocjh/
v-bind="yourObject"
Should do on <my-component v-bind="yourObject"><my-component>
应该在
<my-component v-bind="yourObject"><my-component>
Not sure about <component></component>
.不确定
<component></component>
。 Still digging into Vue.仍在深入研究 Vue。 Try and let us know.
尝试让我们知道。
100% Working Passing object is very simple way from one component to another component. 100% 工作传递对象是从一个组件到另一个组件的非常简单的方法。
Child component Code simple code where StokDetail is an object passing from
子组件代码简单代码,其中 StokDetail 是从
other component其他组件
export default {
props: {
StockDetail: {
type: Object,
default: (()=>{})
},
},
created:function(){
console.log(this.StockDetail);
}
}
</script> ```
> Pass from Parent Component
>
<stock-detail-component v-bind:stock-detail="model.StockDetail"></stock-detail-component>
HTML attributes are case-insensitive, so when using non-string templates, camelCased prop names need to use their kebab-case (hyphen-delimited) equivalents:
such as StockDetail = stock-detail
you can see in this below snapshot
[1]: https://i.stack.imgur.com/tIofC.png
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.