I'm currently exploring how to access the default properties (props
) for a child component. The scenario involves two components, A
and B
. Component B
wraps around component A
, which is passed properties. My goal is to determine the default values of the properties for component A
from its parent component B
, particularly focusing on the specified types for the defaults. Specifically, I want to be able to view the default values and types of component A
in the mounted
function of component B
, assuming that B
will always have exactly one child component.
I've attempted to retrieve the child component's properties using this.$children[0]._props
in the mounted
lifecycle hook, but these properties are the ones that have been set. I also tried accessing the properties earlier in the Vue lifecycle (such as in created
, beforeCreate
, beforeMount
, etc.), but they do not appear to exist until the component is mounted. Inspecting the this.$children[0]
object in the browser console did not reveal any default values for the props, only getter functions that retrieve the override defaults. While I am open to passing additional data to B
to obtain the default properties, I would prefer not to do so as it seems redundant; I should be able to determine the component's "origin" by examining the this.$children[0]
object.
You can find a minimal example here: https://codepen.io/maxschommer/pen/wvaqGjx. I have also included the HTML and JS code below for quick reference.
JS:
Vue.component('A', {
name: "A",
props: {
prop1: {
type: String,
default: "The First Default Value"
},
prop2: {
type: String,
default: 'The Second Default Value'
}
},
template: `<div class="A">
<h1>A Prop 1: {{ prop1 }} </h1>
<h1>A Prop 2: {{ prop2 }} </h1>
</div>`
});
Vue.component('B', {
name: "B",
mounted: function() {
this.$children[0];
// I'd like to find some way to get the default properties
// of the child of this component (A) here (or in computed, etc.). Instead
// this gives the values which were set.
alert(JSON.stringify(this.$children[0]._props));
},
template:
`<div><slot></slot></div>`});
var parent = new Vue({
el: "#app",
template:
`<div class=templateField>
<B>
<A prop1="Overriding" prop2="Defaults"></A>
</B>
</div>`
});
HTML:
<div id="app">
</div>
PS: I'm a bit confused about the difference between components and elements when referring to Vue (I believe components are JS objects and elements are when they are rendered as HTML), so please correct my terminology if I'm mistaken.