Justin
Justin

Reputation: 653

How to get Component Props Dynamically in Vue

I'm using Nuxt.js to build my application.

I'm creating an app that will showcase all our components for documentation purposes. I have the following:

<show-component name="my-component"></show-component>

And my Nuxt.js global.js file imports and sets my components:

import ShowComponent from '../components/ShowComponent.vue'
import MyComponent from '../components/MyComponent.vue'

Vue.component('show-component', ShowComponent)
Vue.component('my-component', MyComponent)

What I would like to do at this point is show on the screen the props that are being used by the component, in this case: my-component

I'm already able to use <my-component> in my template code. How would I go about using it in my JS code? Something like:

let component = getInstanceOf('my-component'); console.log(component.props);

It would be nice to get the full representation of props that I defined on my-component

Upvotes: 4

Views: 9302

Answers (2)

i--
i--

Reputation: 4360

One way to access a component by name from the main Vue instance is this:

let componentName = 'my-component';
const component = this.$options.components[componentName];

If you need to access this from inside another component, you would first have to reference the main Vue instance, which would be this.$root, i.e.

const component = this.$root.$options.components[componentName];

and to access the props of that component:

let props = component.options.props;

I hope that helps.

Upvotes: 0

lukebearden
lukebearden

Reputation: 53

To print an array of props: console.log(Object.keys(component.props))

Upvotes: 1

Related Questions