优雅的处理vue注册全局组件

使用情景:

  有频繁使用的组件 需要进行全局注册

  可以将这些组件都放在components下同一个文件夹下,在此文件夹中建立 一个js文件 代码如下:

  

import Vue from ‘vue‘;

// 修改文件名首字母大写
function changeComponentName (str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

// 获取当前文件夹下的的组件
// require.context 三个参数  第一个表示读取文件的路径  第二个表示是否遍历文件的子目录   第三个表示匹配的文件的正则
const requireComponent = require.context(‘.‘, false, /\.vue$/);

requireComponent.keys().forEach(fileName => {
    const config = requireComponent(fileName);
    const componetName = changeComponentName(
        // 去掉开头 ./  以及后面.vue
        fileName.replace(/^\.\//, ‘‘).replace(/\.\w+$/, ‘‘)
    );
    Vue.component(componetName, config.default || config);
})

最后一步 : 在main.js中引入 当前的js文件,  即可全局使用

原文地址:https://www.cnblogs.com/Mr-Rshare/p/11658786.html

时间: 2024-08-30 15:07:59

优雅的处理vue注册全局组件的相关文章

vue 注册全局组件

注册全局组件有啥好处呢? 提高代码的复用性:哪里需要写哪里,贼方便,就写一个标签:减少代码量:可以再配合slot一起使用,咦~~,舒服 为了让整个项目的可读性,我创建一个文件统一存放全局组件 1.创建common文件夹,文件夹用来存放我们所需要的注册的全局组件 此时我们需要一个index.js文件.上代码 [脑补]我已经再common文件夹下创建好了我引入的这两个文件 这里值得注意的是tabs.name 和 tabItems.name 是啥玩意呀! 诶呀  就是组件命名呗   嗯?需要注意吗?

vue引入全局组件和局部组件的区别以及全局注册公共函数

一,先看看全局组件的引用,就拿最常用的全局的暂无数据来举例,看看全局的是如何实现的. Step1,首先在components创建一个公共的目录,NoDatas目录里边包含index.vue和index.js,index.vue用来写公共的页面,index.js用来导出这个组件. <template> <!-- NoDataWords 可以灵活控制每个页面显示的内容 --> <!-- NoDataHeight 可以灵活控制每个页面的高度 --> <!-- 如果你的页

vue 复习篇. 注册全局组件,和 组件库

初篇 ============================================================== 1. 编写loading组件(components/Loading/index.vue) <template> <div>loading</div> </template> <script> export default { name: 'loading' } </script> 2.注册为全局组件 (c

vue的全局组件和局部组件

<!DOCTYPE html><html><head> <meta charset="utf-8"> <title>全局组件.局部组件</title> <script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script></head><body><div id="a

Vue自动化注册全局组件脚本

今天有一个idea,vue一些组件,可能会全局都用到,我觉得在main.js写 Vue.component(name, instance) 然后很命令式,写着也不好看,想着能够有一个函数可以指定加载比如components下的文件,自动完成全局化注册,想起来就很帅 放代码: export function autoLoadingGlobalComponent() { const requireComponent = require.context( // 其组件目录的相对路径 '../compo

register.vue 注册页面组件

<template> <div class="wrapper"> <navigate :menuList="menuList" :tabIndexList="tabIndexList" :tabIndex="tabIndex" @tabIndexListNav="tabIndexListNav"></navigate> <registerBasicInf

vue定义全局组件

<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title></title> <link href="https://cdn.bootcss.com/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet"> </head> <

VUE注册局部组件

// 局部组件命名规范 /* 1文件夹名大驼峰 MyLocalBtn.vue 2 使用的时候 将驼峰转化为横杠 <my-local-btn></my-local-btn> */ MyLocalBtn.vue局部组件 <template> <div> <div>我输局部组件---{{valuea}}</div> </div> </template> <script> export default {

Vue 局部组件和全局组件的使用

1 <template> 2 <div id="app"> 3 <!--<img alt="Vue logo" src="./assets/logo.png">--> 4 <!--<HelloWorld msg="你妹的是你吗?"/>--> 5 <mtmp></mtmp> 6 <h1>{{ title}}</h1&