import ToastComponent from './toast.vue' let Toast = {}; Toast.install = function(Vue, options = {}) { // extend组件构造器 const VueToast = Vue.extend(ToastComponent) let toast = null function $toast(params) { return new Promise( resolve => { if(!toast) { toast = new VueToast() toast.$mount() document.querySelector(options.container || 'body').appendChild(toast.$el) } toast.show(params) resolve() }) } Vue.prototype.$toast = $toast } if(window.Vue){ Vue.use(Toast) } export default Toast
npm run build 之后就会在根目录下生成dist文件
接下来就可以使用了
demo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no"> <!--引入--> <script src="https://www.jb51.net/node_modules/vue/dist/vue.js"></script> <script src="https://www.jb51.net/dist/vue-toast.js"></script> </head> <body> <div> <h1>vue-toast,{{msg}}</h1> <div> <button @click="test">默认效果</button> </div> </div> <script> var vm = new Vue({ el: "#app", data: { msg: '你好' }, methods: { test() { this.$toast({ title:'消息提示', content: '您有一条新消息', type: 'warning', onShow: ()=>{ console.log('on toast show') }, onHide: ()=>{ console.log('on toast hide') } }) } } }) </script> </body> </html>
总结:
1、使用Vue构造器,通过vue组件来创建一个子类:Vue.extend(component)
2、webpack配置output的path必须为绝对路径
3、webpack基础配置:entry,output,module,plugins