在项目开发中,复用率比较高的组件,为了不频繁手写import组件,我们可以写一个公共的方法自动导入。
第一步,在src的components文件夹下新建一个common.js,内容如下:
import Vue from "vue";
// 首字母转大写
function changeStr(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
const requireComponent = require.context(".", false, /\.vue$/);
requireComponent.keys().forEach(fileName => {
const config = requireComponent(fileName);
const componentName = changeStr(
fileName.replace(/^\.\//, "").replace(/\.\w+$/, "")
);
Vue.component(componentName, config.default || config);
});
第二步,在main.js引入common.js
import "./components/common.js";
第三步,在components文件夹下新建组件,例如:BaseItem.vue
<template>
<div class="list-item">
<div class="item-title">{{ label }}</div>
<div class="item-value">{{ value }}</div>
<slot></slot>
</div>
</template>
<script>
export default {
name: "BaseItem",
props: ["label", "value"]
};
</script>
<style lang="stylus" scoped>
.list-item
display flex
margin-bottom 1.25rem
justify-content flex-start
.item-title
color $color-text-secondary
min-width 5.75rem
.item-value
padding-left 1rem
word-break break-all
</style>
最后,就可以直接在其他组件中使用了(不需要再import):
<base-item></base-item>
BaseItem组件使用效果图: