欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用vue-cli编写vue插件的方法

程序员文章站 2022-04-09 12:49:20
利用vue组件创建模板,使用webpack打包生成插件再全局使用 1、vue init webpack-simple 生成项目目录 2、调整目录结构 3、修改we...

利用vue组件创建模板,使用webpack打包生成插件再全局使用

1、vue init webpack-simple 生成项目目录

2、调整目录结构

使用vue-cli编写vue插件的方法

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:[]
} 

开发一个toast插件,可以借助npm平台发布,在这里就不做过多的说明了

toast.vue

<template>
 <transition name="toast-fade">
  <div class="toast"
   :class="objclass" 
   v-show="isactive"
   @mouseenter="onmouseenter"
   @mouseleave="onmouseleave"
   >
   <button class="toast-close-button" @click="hide">×</button>
   <div class="toast-container">
    <div class="toast-title">{{title}}</div>
    <div class="toast-content">{{content}}</div>
   </div>
  </div>
 </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 run build 之后就会在根目录下生成dist文件

使用vue-cli编写vue插件的方法

接下来就可以使用了

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>
 <div id="app">
  <h1>vue-toast,{{msg}}</h1>
  <div class="demo-box">
   <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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。