我正在重构我的应用程序中的一些代码,结果发现,以下逻辑在许多组件中重复出现。
import component1 from '...'
import component2 from '...'
import component3 from '...'
//...many others
export default {
//other data
components: {
component1,
component2,
component3
//...
}
}
是否存在更短的方法来清理我的代码? 感谢您的宝贵时间
最佳答案
以下是 3 种方法。顺便说一句,我更喜欢方法 3。
Method 1
在我的案例中创建一个js
文件dynamic_imports.js
:
export default function (config) {
let registered_components = {}
for (let component of config.components) {
registered_components[component.name] = () => System.import(`../${config.path}/${component.file_name}.vue`)
}
return registered_components
}
在有许多组件导入和注册的组件中
import dynamic_import from '@/services/dynamic_imports' //importing the above file
let components = dynamic_import({
path: 'components/servers',
components: [
{ name: 'server-one', file_name: 'serverOne' },
{ name: 'server-two', file_name: 'serverTwo' },
]
})
export default {
//...other code
components: components
}
因此,您将使用“干净的代码”导入并注册您的组件。 但是注意这对我有用,也许它需要稍微修改一下才能满足您的需求,以理解:
属性path
表示将在该路径中查找file_name
中指定的名称。name
属性是您注册的名称组件
Method 2 If you don't like the above look below to another way:
function import_component(cmp_name){
return System.import(`@/components/${cmp_name}.vue`);
}
export default{
components: {
'component1': () => import_component('componentOne'),
'component2': () => import_component('componentTwo'),
'component3': () => import_component('componentThree')
}
}
Method 3 If again you are saying: This is not a cleaner way,take a look below but keep in mind that if you are working in team and skills differ,then some programmers will be a little bit confused.
dynamic_imports.js
export default function ({path, file_names, component_names}) {
let registered_components = {}
for (let [index, file_name] of file_names.entries()) {
registered_components[component_names[index]] = () => System.import(`../${path}/${file_name}.vue`)
}
return registered_components
}
在您的组件中
import dynamic_import from '@/services/dynamic_imports'
let components = dynamic_import({
path: 'components/servers',
file_names: ['serverOne', 'serverTwo'],
component_names: ['server-one', 'server-two']
})
export default {
components: components
}
关于javascript - vue.js 中多个导入和注册的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51004628/