vue3组件配置相关,文件目录,自动注册,引入等

组件目录

全局组件的注册和引入

全局组件注册

components/index.js

【方式一:先引入后注册】
import BgImage from "@/components/global/web-background/bg-image.vue"; 
import BackTop from "@/components/global/back-top/back-top.vue";

const install = (app) => {
    app.component("BgImage", BgImage);
    app.component("BackTop", BackTop);
};
export default install;


【方式二:直接在component里进行引入和注册,需要异步操作】
import { defineAsyncComponent } from "vue";  //此方式需要调用vue提供的此异步api

const install = (app) => {
    app.component("BgImage", defineAsyncComponent(()=>import("@/components/global/web-background/bg-image.vue")));
    app.component("BackTop", defineAsyncComponent(()=>import("@/components/global/back-top/back-top.vue")));
};
export default install;

全局组件引入

/main.js

const app=createApp(App)
import globalComponents from "@/components/index"

app.use(globalComponents)

全局组件自动注册

/**
 * global文件夹:用于存放全局组件,组件会自动注册,无需手动注册
 * regional文件夹:用于存放区域自用型组件,需要在使用时手动注册
 *
 * 此index.js主要用于global下组件的自动注册
 */

/**
 * 关于组件命名:大驼峰BackTop,小驼峰backTop,短横线-分隔back-top,下划线_分隔均可。
 * 推荐短横线 - 分隔命名 back-top.vue
 */

//转换组件命名为大驼峰形式 ↓↓
const toBigUpper=(value)=>{
    return value.replace(/^(\w)|[-_](\w)/g,(matchedValue,$1,$2)=>{
        if($1||$2){
            return $1?$1.toUpperCase():$2.toUpperCase()
        }else{
            return value
        }
    })
}

/**
 * 利用webpack的require.context()语法
 * require.context(directory,useSubdirectories,regExp)
 * directory: 检索的目录
 * useSubdirectories:是否检索子文件夹
 * regExp: 匹配文件的正则表达式,一般是文件名
 * 例如 require.context("@/views/components",false,/.(vue|js)$/)
 */
const files = require.context("./global", true, /\.vue$/); // 获取global文件下下所有组件对象

const install = (app) => {
    files.keys().forEach((key) => {
        // 解析组件对象,注册为全局组件
        const config = files(key);
        const name = key.replace(/^(\.\/)|(\.\w+)$/g, "").split("/").pop();
        app.component(toBigUpper(name), config.default || config);
    });
};
export default install;

posted @ 2022-09-19 17:21  huihuihero  阅读(13)  评论(0)    收藏  举报