详解使用webpack打包编写一个vue-toast插件(2)

实践

需求:一个toast弹层功能

1、template.vue。提供html模板

<template>
 <section class="toast-container" :class="visible?'fade-in':'fade-out'">
  <div class="toast">
   <span>{{message}}</span>
  </div>
 </section>
</template>
<script>
 export default {
  name:'tmp',
  data(){
   return{
    visible:true,
    message:'默认提示语'
   }
  }
 }
</script>
<style>
</style>

2、index.js

import ToastComponent from './vue-toast.vue'

let Toast = {}
Toast.install = function(Vue,options){
 var opt={
  duration:3000,

 }
 for(var key in options){
  opt[key] = options[key];
 }
 Vue.prototype.$toast=function(msg,option){
  if(typeof option =='object'){
   for(var key in option){
    opt[key]=option[key]
   }
  }
  const ToastController= Vue.extend(ToastComponent);

  var instance = new ToastController().$mount(document.createElement('div'))

  instance.message = msg;
  instance.visible = true;

  document.body.appendChild(instance.$el)
  setTimeout(()=>{
   instance.visible=false;
   document.body.removeChild(instance.$el)
  },opt.duration)
 }
 Vue.prototype.$toast['show']=function(msg,option){
  Vue.prototype.$toast(msg,option);
 }
}
if(window.Vue){
 Vue.use(Toast)
}

export default Toast;

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 for mobile{{msg}}</h1>
 <div class="demo-box">
  <button @click="test">默认效果</button>
  <button>5s后自动关闭</button>
  <button>消失后执行回调</button>
 </div>
</div>
<script>
 var vm = new Vue({
  el:"#app",
  data:{
   msg:'你好'
  },
  methods:{
   test(){
   // 使用
    this.$toast.show('再来',{
     duration:1000
    })
   }
  }
 })
</script>
</body>
</html>

总结

  1. 使用基础Vue构造器,通过vue组件来创建一个子类:Vue.extend(component)
  2. 编写vue插件的四种方法:常用-Vue.prototype.$method, 其他:Vue.method,Vue.mixin(option),Vue.directive(‘method',option)
  3. webpack配置output的path必须为绝对路径
  4. webpack配置三大属性,entry,output,module,plugins

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