在日常开发中,有一些组件是比较常用,但是为了避免在开发过程中不停地引入,或者在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>