直接在项目中使用Vue.use来使用自己的公共组件

410 阅读1分钟

小知识,大挑战!本文正在参与“        程序员必备小知识        ”创作活动

之前一篇讲解了怎么搭建属于自己的组件库,那么如果不通过npm --save xxx 自己的组件,怎么直接在项目中通过use来使用自己写的公共组件呢。

使用:

在公共组件中新建一个index.js 文件 在这里插入图片描述 index文件的内容如下:

import commonRadio from '../components/zrd/commonRadio';
import commonSelect from '../components/zrd/commonSelect';
import commonMuitSelect from '../components/zrd/commonMuitSelect';
import upload from '../components/Upload/upload';
import commonCurrentUpload from "../components/df/commonCurrentUpload";
import commonGetSelect from "../components/df/commonGetSelect";

const components = [commonRadio, commonSelect, upload, commonMuitSelect, commonCurrentUpload, commonGetSelect];

const component = {
    install: function (Vue) {
        components.map(component => {
            Vue.component(component.name.replace(/([A-Z])/g, "-$1").toLowerCase(), component)
        })
    }

}

// // 导出该组件
export default component

首先引入这些组件,然后通过install安装这些组件,这些组件里面必须写上name

在这里插入图片描述 然后在index中,通过正则将组件的名字转化成 - 形式,如commonGetSelect会转化为common-get-select,然后就可以在其他组件中去使用。

在main.js中去注册:

import commonUi from "@/components/index";
Vue.use(commonUi);

通过这样全局注册之后,所有的组件都不再需要在页面再引入和在components里面注册了,可以直接将common-get-select当做一个标签一样使用<common-get-select> </common-get-select>

详解:

以下代码通过map将每一个组件循环注册,但是这样使用的时候我们需要写成<commonGetSelect></commonGetSelect>这种形式,所以需要将组件的名字通过正则表达式component.name.replace(/([A-Z])/g, "-$1").toLowerCase()转化成<common-get-select> </common-get-select>这样,以达到我们的使用规范。

那么,由此可知,我们也可以直接在组件的name中写成:name:'common-get-select'。这样也可以直接写成以下形式:

install: function (Vue) {
        components.map(component => {
            Vue.component(component.name, component)
        })
    }