简体   繁体   English

Vue.js:动态获取已注册的组件

[英]Vue.js: Dynamically get registered components

Here's a jsBin showing my scenario 这是一个显示我的场景的jsBin

I have a selector <component :is="selectedComponent"></component> , and a <select v-model="currentComponent">...</select> which allows me to select which one is shown. 我有一个选择器<component :is="selectedComponent"></component> ,还有一个<select v-model="currentComponent">...</select> ,它允许我选择显示哪一个。

Currently I am maintaining a separate list of components that looks like so: 目前我正在维护一个单独的组件列表,如下所示:

var componentList = [
  { name: 'Component A', id: 'component-a' },
  { name: 'Component B', id: 'component-b' }
]; 

And that list is fed into the select element's <option> items with id as the value, and name as the text. 并且该列表被输入到select元素的<option>项中,其中id为值, name为文本。

This is not very DRY as I need to maintain this list with each new component. 这不是很干,因为我需要用每个新组件维护这个列表。 I would like to abstract the component list in a way that is more elegant. 我想以更优雅的方式抽象组件列表。

I tried doing in the app: 我尝试在应用程序中执行:

var vm = Vue.extend({
  components: {
    'component-a': ComponentA,
    // etc.
  }
  computed: {
    componentList: function() {
      // map this.$options.components or something else?
    }
  }
});

But I am getting nowhere. 但我无处可去。 Any tips? 有小费吗? Best practices? 最佳做法?

Thank you! 谢谢!

I'm doing something similar in my current project, I have all my components in a folder called 'components' and inside that folder, an index.js file that exports all the components, like this: 我在我当前的项目中做了类似的事情,我将所有组件放在一个名为'components'的文件夹中,并在该文件夹中,一个index.js文件导出所有组件,如下所示:

export component1 from './component1.vue'
export component2 from './component2.vue'

...etc ...等等

and inside my vue component I import them all like this: 在我的vue组件中,我将它们全部导入:

import * as components from '../components'

var vm = new Vue({
  components: components,
  computed: {
    componentsList() {
       return Object.keys(components)
    }
  }
})

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

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