이 글에서는 주로 vue-cli를 사용하여 vue 플러그인을 작성하는 방법을 소개하고 참고하겠습니다.
vue 구성 요소를 사용하여 템플릿을 만들고, webpack을 사용하여 플러그인을 패키징하고 생성한 다음 전역적으로 사용하세요
1. vue init webpack-simple은 프로젝트 디렉터리를 생성합니다
2. 디렉터리 구조를 조정합니다
3. . webpack.config.js 수정
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'vue-toast.js', // 打包后的格式(三种规范amd,cmd,common.js)通过umd规范可以适应各种规范,以及全局window属性 libraryTarget:'umd', }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, ] }, plugins:[] }
npm 플랫폼의 도움으로 출시할 수 있는 토스트 플러그인을 개발하세요. 여기서는 너무 많은 설명을 하지 않겠습니다
toast.vue
<template> <transition name="toast-fade"> <p class="toast" :class="objClass" v-show="isActive" @mouseenter="onMouseenter" @mouseleave="onMouseleave" > <button class="toast-close-button" @click="hide">×</button> <p class="toast-container"> <p class="toast-title">{{title}}</p> <p class="toast-content">{{content}}</p> </p> </p> </transition> </template> <script> export default { data: () => ({ list: [], title: null, content: null, type: null, isActive: false, timer: null, onShow: () => {}, onHide: () => {} }), computed: { objClass () { // 样式'success, error, warning, default' return this.type ? 'toast-' + this.type : null } }, methods: { // 显示 show (params) { let {content, title, onShow, onHide, type} = params this.type = type this.content = content this.title = title this.onShow = onShow this.onHide = onHide this.isActive = true this.setTimer() }, // 隐藏 hide () { this.isActive = false }, // 计时器 setTimer () { clearTimeout(this.timer) this.timer = setTimeout(() => { this.isActive = false }, 4000) }, // 鼠标移至组件时保持显示状态 onMouseenter () { clearTimeout(this.timer) }, // 鼠标移开组件时重新定时 onMouseleave () { if (this.isActive) this.setTimer() } }, watch: { isActive (val) { if (val && typeof this.onShow === 'function') { this.onShow() } else if (!val && typeof this.onHide === 'function') { this.onHide() } } } } </script> <style> .toast { position: fixed; top: 10px; right: 10px ; display: block; width: 300px; overflow: hidden; box-shadow: 0 0 6px #999; opacity: .8; border-radius: 3px 3px; padding: 15px 15px 15px 15px; background-position: 15px center; background-repeat: no-repeat; color: #333; background-color: #f0f3f4; } .toast-success { color: #fff; background-color: #51a351; padding: 15px 15px 15px 50px; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADsSURBVEhLY2AYBfQMgf///3P8+/evAIgvA/FsIF+BavYDDWMBGroaSMMBiE8VC7AZDrIFaMFnii3AZTjUgsUUWUDA8OdAH6iQbQEhw4HyGsPEcKBXBIC4ARhex4G4BsjmweU1soIFaGg/WtoFZRIZdEvIMhxkCCjXIVsATV6gFGACs4Rsw0EGgIIH3QJYJgHSARQZDrWAB+jawzgs+Q2UO49D7jnRSRGoEFRILcdmEMWGI0cm0JJ2QpYA1RDvcmzJEWhABhD/pqrL0S0CWuABKgnRki9lLseS7g2AlqwHWQSKH4oKLrILpRGhEQCw2LiRUIa4lwAAAABJRU5ErkJggg==") !important; } .toast-error { color: #fff; background-color: #bd362f; padding: 15px 15px 15px 50px; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHOSURBVEhLrZa/SgNBEMZzh0WKCClSCKaIYOED+AAKeQQLG8HWztLCImBrYadgIdY+gIKNYkBFSwu7CAoqCgkkoGBI/E28PdbLZmeDLgzZzcx83/zZ2SSXC1j9fr+I1Hq93g2yxH4iwM1vkoBWAdxCmpzTxfkN2RcyZNaHFIkSo10+8kgxkXIURV5HGxTmFuc75B2RfQkpxHG8aAgaAFa0tAHqYFfQ7Iwe2yhODk8+J4C7yAoRTWI3w/4klGRgR4lO7Rpn9+gvMyWp+uxFh8+H+ARlgN1nJuJuQAYvNkEnwGFck18Er4q3egEc/oO+mhLdKgRyhdNFiacC0rlOCbhNVz4H9FnAYgDBvU3QIioZlJFLJtsoHYRDfiZoUyIxqCtRpVlANq0EU4dApjrtgezPFad5S19Wgjkc0hNVnuF4HjVA6C7QrSIbylB+oZe3aHgBsqlNqKYH48jXyJKMuAbiyVJ8KzaB3eRc0pg9VwQ4niFryI68qiOi3AbjwdsfnAtk0bCjTLJKr6mrD9g8iq/S/B81hguOMlQTnVyG40wAcjnmgsCNESDrjme7wfftP4P7SP4N3CJZdvzoNyGq2c/HWOXJGsvVg+RA/k2MC/wN6I2YA2Pt8GkAAAAASUVORK5CYII=") !important; } .toast-warning { color: #fff; background-color: #f89406; padding: 15px 15px 15px 50px; background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGYSURBVEhL5ZSvTsNQFMbXZGICMYGYmJhAQIJAICYQPAACiSDB8AiICQQJT4CqQEwgJvYASAQCiZiYmJhAIBATCARJy+9rTsldd8sKu1M0+dLb057v6/lbq/2rK0mS/TRNj9cWNAKPYIJII7gIxCcQ51cvqID+GIEX8ASG4B1bK5gIZFeQfoJdEXOfgX4QAQg7kH2A65yQ87lyxb27sggkAzAuFhbbg1K2kgCkB1bVwyIR9m2L7PRPIhDUIXgGtyKw575yz3lTNs6X4JXnjV+LKM/m3MydnTbtOKIjtz6VhCBq4vSm3ncdrD2lk0VgUXSVKjVDJXJzijW1RQdsU7F77He8u68koNZTz8Oz5yGa6J3H3lZ0xYgXBK2QymlWWA+RWnYhskLBv2vmE+hBMCtbA7KX5drWyRT/2JsqZ2IvfB9Y4bWDNMFbJRFmC9E74SoS0CqulwjkC0+5bpcV1CZ8NMej4pjy0U+doDQsGyo1hzVJttIjhQ7GnBtRFN1UarUlH8F3xict+HY07rEzoUGPlWcjRFRr4/gChZgc3ZL2d8oAAAAASUVORK5CYII=") !important; } .toast:hover { opacity: 1; box-shadow: 0 0 18px #888; transition: all 200ms ease; } .toast-container { vertical-align: middle; } .toast-fade-enter, .toast-fade-leave-active { opacity: 0; transform: translateX(100%); } .toast-fade-leave-active, .toast-fade-enter-active { transition: all 400ms cubic-bezier(.36,.66,.04,1); } .toast-title { font-size: 14px; font-weight: bold; } .toast-close-button { padding: 2px 2px; border: none; background: transparent; position: relative; right: -10px; top: -15px; float: right; font-size: 20px; font-weight: bold; color: #ffffff; -webkit-text-shadow: 0 1px 0 #ffffff; text-shadow: 0 1px 0 #ffffff; -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80); filter: alpha(opacity=80); } </style>
index.js
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 실행 빌드는 루트 디렉토리에 dist 파일을 생성합니다
다음에 사용할 수 있습니다
demo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no"> <!--引入--> <script src="node_modules/vue/dist/vue.js"></script> <script src="dist/vue-toast.js"></script> </head> <body> <p id="app"> <h1>vue-toast,{{msg}}</h1> <p class="demo-box"> <button @click="test">默认效果</button> </p> </p> <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(컴포넌트)
2. 출력을 구성하는 웹팩의 경로는 절대 경로여야 합니다
3. 웹팩의 기본 구성: 항목, 출력, 모듈, 플러그인
위 내용은 제가 컴파일한 것입니다. . 앞으로도 도움이 되길 바랍니다.
관련 기사:
위 내용은 vue-cli를 사용하여 vue 플러그인을 작성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!