vue高复用组件自动import

在项目开发中,复用率比较高的组件,为了不频繁手写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组件使用效果图:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值