Reputation: 2303
I have a component tab-panel
and a component tab
, and need to ensure that tabs
are only rendered if inside of a tab-panel
.
How do I check the type of the parent to enforce this?
Upvotes: 1
Views: 2036
Reputation: 55644
You can check the name of the parent component via this.$parent.$options.name
.
Here's and example:
Vue.config.devtools = false;
Vue.config.productionTip = false;
Vue.component('tab', {
template: `<div>tab</div>`,
created() {
if (this.$parent.$options.name !== 'tab-panel') {
throw new Error('tab must be in tab-panel!')
} else {
console.log('tab is in tab-panel :)')
}
}
})
Vue.component('tab-panel', {
template: `<div>tab-panel<tab></tab></div>`,
})
new Vue({
el: '#app',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<tab-panel></tab-panel>
<tab></tab>
</div>
Upvotes: 4