首先您需要导入/注册所有组件,您可以像下面这样在组件级别执行此操作,也可以全局执行此操作。
export default {
components: {
ColumnA: () => import('../columns/ColumnA'),
ColumnB: () => import('../columns/ColumnB'),
ColumnC: () => import('../columns/ColumnC'),
ColumnD: () => import('../columns/ColumnD'),
}
}
接下来,您必须确保可以将您的状态映射到 column-a 以匹配组件名称。如果是这种情况,您可以使用:
computed: {
column() {
return this.$store.state.column;
}
}
如果没有,您将不得不创建地图:
computed: {
column() {
const mappedComponents = {
myStateKeyForColumnA: 'column-a',
myStateKeyForColumnB: 'column-b',
myStateKeyForColumnC: 'column-c',
myStateKeyForColumnD: 'column-d',
}
return mappedComponents[this.$store.state.column];
}
}
编辑
要全局注册组件,可以使用require.context。
在 main.js 中
const context = require.context('./path/to/columns', true, /\.vue$/)
for (const key of context.keys()) {
// key gives us the file name, ie. ./ColumnA.vue
// the code below, to register the component name is based on the above patterh
// likely you will have to modify this
Vue.component(key.slice(2).split('.')[0], () => context(key))
}