繁体   English   中英

如何在Vue中动态获取组件道具

[英]How to get Component Props Dynamically in Vue

我正在使用Nuxt.js来构建我的应用程序。

我正在创建一个应用程序,该应用程序将展示我们所有用于文档目的的组件。 我有以下内容:

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

我的Nuxt.js global.js文件导入并设置了我的组件:

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

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

我现在想做的是在屏幕上显示组件正在使用的props ,在这种情况下: my-component

我已经可以在模板代码中使用<my-component>了。 我将如何在JS代码中使用它? 就像是:

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

得到我在my-component上定义的props的完整表示会很高兴

要打印道具阵列: console.log(Object.keys(component.props))

通过名称从主Vue实例访问组件的一种方法是:

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

如果需要从另一个组件内部访问它,则首先必须引用主Vue实例,即this.$root ,即

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

并访问该组件的道具:

let props = component.options.props;

希望对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM