首先,我最近写了四个组件了,代码都在我之前的博客当中。
我是参考了elementUI的源码来写的。不然,自己写还不知道什么时候能写出来。非常感谢elementUI的开源贡献。
这里附上elementUI开源地址:
https://github.com/ElemeFE/element
下面是介绍我自己的代码部分。
一、首先是项目结构,声明,我是在个人项目上直接开发,未打算发布到npm上面。所以我尽可能的是把源码分享到csdn上面。
从结构上没啥可看的。
index.js是安装暴露文件
安装方式:(是不是很像elementUI)
//个人开发ui组件,以插件方式开发 import dhtui from "@/components/dhtVueUI/index"; Vue.use(dhtui, { zIndex: 4000 });
二、index.js内容
我基本上都注释了,所以不废话了,如果这样还看不懂,那么我只能说各位还有很长的距离要走(手动狗头)
//批量注册部分
import Img from "./img/index"; //替代img标签
import Text from "./text/index"; //替代p标签
//需要独立注册部分
import Loading from "./loading/install"; //加载标签
//批量注册部分
const components = [Img, Text];
// eslint-disable-next-line no-unused-vars
const install = function(vue, opts = {}) {
//初始化部分
vue.prototype.$dhtUI = {
zIndex: opts.zIndex || 2000
};
//指令注册部分
vue.use(Loading.directive);
//批量组件注册
components.forEach(component => {
vue.component(component.name, component);
});
//挂载到vue原型上
vue.prototype.$dhtLoading = Loading.service;
};
//代码意思上是指必须要vue已经存在才可以
if (typeof window !== "undefined" && window.Vue) {
install(window.Vue);
}
export default {
//版本
version: "1.0.0",
//全注册
install,
//局部注册
Img,
Text,
Loading
};
三、每个组件文件夹下的结构
这里用loading组件文件夹为例,因为这个更加复杂,有参考性
loading分为进度条函数式加载方式和指令方式,分别将代码放在不同的文件中。
install.js是安装文件,其他文件夹则是index.js(这个个人喜好问题,不过团队开发最好是统一)
代码:
import service from "./progress"; import directive from "./mask/directive"; export default { install(vue) { vue.use(directive); vue.prototype.$dhtLoading = service; }, service, directive };
普通安装文件:
import img from "./img.vue"; img.install = function(vue) { vue.component(img.name, img); }; export default img;
四、 废话部分
也没啥可说的了。主要是给大家参考的。代码还是很烂。毕竟我也才半年前端。(轻喷)