关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

如何从0开发一个Vue组件库并发布到npm(下)

发布时间:2023-06-26 15:00:36

5、开发一个toast弹窗



  • toast模块:vueComponentDi/packages/toast/index.vue

type只支持warning和success


  { {message}}  div> template> export default {  data(){  return {  message:'',  show:false,  type:''  }  } } script> .di-toast{  width: 60%;  width: 200px;  background: rgb(15, 15, 15);  padding:3px;  text-align: center;  color: #fff;  border-radius: 10px;  position: fixed;  left: calc(50% - 100px);  top: 200px; } .di-toast--warning{  background: #FDF6EC;  color: #E6A28B; } .di-toast--success{  background: #F0F9EB;  color: #93C26D; } style>    toast模块导出:vueComponentDi/packages/toast/index.js因为toast弹窗需要在vue中支持this.$toast调用,所以用了Vue.extend方法,这个 API 在日常开发中很少使用,一般在开发组件的时候它才能派上用场,官方定义:使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象import toast from './index.vue' toast.install = (Vue) => {  const toastConstructor = Vue.extend(toast);//使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。  let $vm = new toastConstructor();//将这个子类实例化  let $el = $vm.$mount().$el;//$vm执行$mount()手动挂载会返回一个带有$el的对象,$el就是一个dom对象  document.querySelector("body").appendChild($el);//将这个dom对象添加到body中  //在Vue原型上注入$toast方法  Vue.prototype.$toast = (option) => {  $vm.show = true  if (!(option instanceof Object)) {  //如果传的不是对象直接弹出  $vm.message = option  } else {  $vm.message = option.message  $vm.type = option.type  }  setTimeout(() => {  $vm.show = false  }, 2000)  } } export default toast    聚合导出:vueComponentDi/index.jsimport diButton from "./packages/button" import toast from "./packages/toast" export {  diButton,  toast }    vuetest中使用toast  按钮di-button>  div> template> // @ is an alias to /src import Vue from "vue"; import { diButton, toast } from "vuecomponentdi"; Vue.use(diButton); Vue.use(toast); export default {  name: "Home",  methods: {  toast() {  // this.toast("这是一个普通弹窗");  // this.$toast({  // message: "这是一个成功弹窗",  // type: "success",  // });  this.$toast({  message: "这是一个警告弹窗",  type: "warning",  });  },  }, }; script>     6、发布到npm公有配置组件开发完成需要发布到npm以便于别人使用;因为发布的是公有包,所以需要在vueComponentDi/package.json中配置"publishConfig": {  "access": "public"  },    完整package.json:{  "name": "vuecomponentdi",  "version": "1.0.0",  "description": "",  "main": "index.js",  "scripts": {  "test": "echo \"Error: no test specified\" && exit 1"  },  "keywords": [],  "author": "",  "license": "ISC",  "devDependencies": {  "eslint": "^6.7.2",  "eslint-plugin-vue": "^8.2.0"  },  "publishConfig": {  "access": "public"  } }     发布npm发布很简单,只需要两个命令:npm login npm publish    执行npm login需要你有npm账号,可以到 npm官网 注册发布完成之后就可以在任何一个vue2项目中安装使用了:npm install vuecomponentdi    git地址: vue组件开发" _ue_custom_node_="true">

/template/Home/leiyu/PC/Static