基础组件的自动化全局注册

在日常开发中,有一些组件是比较常用,但是为了避免在开发过程中不停地引入,或者在main.js中注册,,或者每添加一个组件就需要手动注册一次。则直接进行自动化全局注册。

1、自定义文件夹:

在src下新建一个components文件夹,用于存放组件。并新建一个用于存放需要自动化全局注册的组件,例如base。

2.在base文件夹下定义index.js,具体代码如下示:

 

// 将/components/global里面的组件设为全局组件
import Vue from 'vue'
import $lodash from '../utils/lodash'


const requireComponent = require.context(
  // 其组件目录的相对路径
  './',
  // 是否查询其子目录
  true,
  // 匹配基础组件文件名的正则表达式
  /[A-Z]\w+\.(vue|js)$/
)
const componentPrefix = 'tt'; // 公共组件前缀
requireComponent.keys().forEach(fileName => {
  // 获取组件配置
  const componentConfig = requireComponent(fileName)

  // 获取组件的 PascalCase 命名
  const componentName = componentPrefix + $lodash.upperFirst(
    $lodash.camelCase(
      // 剥去文件名开头的 `'./` 和结尾的扩展名
      fileName.replace(/^\.\/(.*)\/Index\.\w+$/, '$1')
    )
  )
  // 全局注册组件
  Vue.component(
    componentName,
    // 如果这个组件选项是通过 `export default` 导出的,
    // 那么就会优先使用 `.default`,
    // 否则回退到使用模块的根。
    componentConfig.default || componentConfig
  )
})

3、在main.js中引入index.js文件

 

import './components/index'


new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')

全局注册的行为必须在根 Vue 实例 (通过 new Vue) 创建之前发生

4、直接在需要的地方使用该组件即可

 <tf-countup
                class="value"
                :end-val="source.value || 0"
                :decimals="source.decimals"
                :options="{ separator: '' }"
              ></tf-countup>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值