Vue でオブジェクトを props として渡すにはどうすればよいでしょうか。これは簡単な作業だと想像しますが、どうやらそうではないようです。
ファイルに次のコードがあります.vue
:
<template>
<div id="scatter"></div>
</template>
<script>
export default {
props: {
data: {
type: Object,
default: () => ({}),
},
},
mounted() {
console.log(this.data);
},
};
</script>
HTML では、次のようにプロパティを渡そうとしますdata
。
<component :data="{x:1}"></component>
コンソールにログインしようとすると、結果は空のオブザーバー オブジェクトのみになります。
ベストアンサー1
オブジェクトをプロパティとして渡すのは想像するほど簡単なので、問題はコードの他の場所にあると思います。
// 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>
実際に動作している様子を示すフィドルを以下に示します。https://jsfiddle.net/tk9omyae/