I have a child component that needs to accept a value given in the component's parent's $options
object as a possible default value.
In the background, the component should be able to receive its data through a prop or from a configuration. However, there is existing code that expects the data to be passed as an option to the main Vue instance.
The new way of creating the Vue instance looks like this:
new Vue({
el: '#app',
render: h => h(MainComp, {
props: {
document: 'data.json'
}
})
});
The component is designed to calculate the prop's value from a config file if it is not provided (or set it to a default value of null
):
import Config from './config.js';
[...]
props: {
document: {
default: Config.document || null
},
This setup works well.
However, in the legacy code, the Vue instance used to be created like this:
new Vue({
el: '#app',
document: 'data.json',
render: h => h(MainComp)
});
and the data was accessed in the data()
function by using
this.$parent.$options['document']
.
My initial thought was to incorporate this same code into the new default
:
default: this.$parent.$options['document'] || Config.document || null
but it turned out that it doesn't work, as the docs mention that "props are validated before a component instance is created, so instance properties [are not] available".
So I attempted to define my "special default" through the data()
function like this:
data() {
return {
document: document || this.$parent.$options['document']
};
},
Unfortunately, Vue rightly points out: "The data property "document" is already declared as a prop. Use prop default value instead."
How can I break free from this cycle?