1、创建项目
此处我使用的vuecli3命令
vue create myplugins
2、写组件
写了一个notice组件,效果是弹出一个提示框,可以通过vue的方法进行调用,如this.$notice("xxxxx")
<template> <div class="notice"> <transition name="slide-fade"> <div class="content" v-if=show_me> {{ content }} <div class="close" v-if="closed" @click="show_me = false;close()"></div> </div> </transition> </div> </template> <script> export default { name: ‘notice‘, data() { return { // visible: false, content: ‘‘, duration: 3000, show_me: true, closed: true } }, methods: { setTimer() { setTimeout(() => { this.show_me = false; this.close() // 3000ms之后调用关闭方法 }, this.duration) }, close() { // this.visible = false setTimeout(() => { this.$destroy(true) if(this.$el.parentNode) this.$el.parentNode.removeChild(this.$el) // 从DOM里将这个组件移除 }, 300) } }, mounted() { this.setTimer() // 挂载的时候就开始计时,3000ms后消失 } } </script> <style scoped> .content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 1px solid #edf2fc; background: #edf2fc; padding: 10px 10px 10px 15px; box-sizing: border-box; border-radius: 5px; } .close { display: inline-block; width: 14px; height: 1px; background: #909399; transform: rotate(45deg); -webkit-transform: rotate(45deg); vertical-align: middle; cursor: pointer; } .close::after { content: ‘‘; display: block; width: 14px; height: 1px; background: #909399; transform: rotate(-90deg); -webkit-transform: rotate(-90deg); } .close:hover { background-color: #409EFF; } .close:hover::after { background-color: #409EFF; } .slide-fade-enter-active { transition: all .3s ease; } .slide-fade-leave-active { transition: all .3s cubic-bezier(1.0, 0.5, 0.8, 1.0); } .slide-fade-enter, .slide-fade-leave-to { transform: translate(-50%, calc(-50% - 20px)); opacity: 0; } </style>
3、在同目录下创建index.js
import Vue from ‘vue‘ import notice from ‘./notice.vue‘ const NoticeConstructor = Vue.extend(notice) // 直接将Vue组件作为Vue.extend的参数 let nId = 1 const Notice = (content,showClose = true) => { let id = ‘notice-‘ + nId++ const NoticeInstance = new NoticeConstructor({ data: { content: content,//内容 closed:showClose//是否显示关闭 } }) // 实例化一个带有content内容的Notice NoticeInstance.id = id NoticeInstance.vm = NoticeInstance.$mount() // 挂载但是并未插入dom,是一个完整的Vue实例 document.body.appendChild(NoticeInstance.vm.$el) // 将dom插入body NoticeInstance.vm.$el.style.zIndex = nId + 1001 // 后插入的Notice组件z-index加一,保证能盖在之前的上面 return NoticeInstance.vm } export default { install: Vue => { Vue.prototype.$notice = Notice // 将Notice组件暴露出去,并挂载在Vue的prototype上 } }
4、修改package.json
"scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lib": "vue-cli-service build --target lib --name mynpm --dest lib ./src/notice/index.js" }, "main": "dist/mynpm.common.js", "private": false, "license": "MIT",
5、创建并修改vue.config.js
css: { extract: false, // 是否使用css分离插件 ExtractTextPlugin },
6、修改ignore
node_modules public/ vue.config.js babel.config.js *.map *.html src/
7、运行 lib 命令打包
8、登录、发布npm
npm login npm publish
原文:https://www.cnblogs.com/usebylgb/p/10900406.html