自定义Vue插件

今天咱们来玩一下vue中的自定义组件,此案例直接通过script引入js的形式定义组件
我是简单的写了一个弹出框的小插件

css样式–这就不需要解释了吧,强撸

<style>
    button{
      width:100px;
      height:30px;
      background: red;
      border-radius:10px;
      color: #fff;
    }
    .dialog{
      width:300px;
      height:200px;
      background: rgba(0,0,0,.3);
      border-radius:10px;
      position: fixed;
      top:50%;
      left:50%;
      transform: translate(-50%,-50%);
    }
    .dialog button{
      position: absolute;
      right:-5px;
      width: 20px;
      height:20px;
      border-radius:10px;
      top:-5px;
      text-align: center;
      line-height:10px;
    }
    .dialog p{
      text-align: center;
    }
  </style>

html结构

<div id="app">
    <button @click="showDialog">自定义弹框</button>
</div>

组件核心js

    var Alert = {}
    //1.0  此处的install方法 是vue中规定好的
    Alert.install = function(){
      //2.0 通过extend来定义自己的组件模板,最终会得到组件模板构造函数
      var AlertConstructor = Vue.extend({
        template:'<div v-if="isShow" class="dialog"><p>{{msg}}</p><button @click="close">x</button></div>',
        data(){
          return {
            msg:'hello',
            isShow:false
          }
        },
        methods:{
          close(){
            this.isShow = false
          }
        }
      })
      //  3.0 通过new AlertConstructor 会得到组件对象
      var Instance = new AlertConstructor({
        el:document.createElement('div')
      })
      //  4.0 将$alert方法挂载到原型上,外界可以访问到,并且将自己定义的组件append到body中
      Vue.prototype.$alert = function(text){
        document.body.appendChild(Instance.$el)
        Instance.isShow = true
        Instance.msg = text
      }
    }
    Vue.use(Alert)
    var vm = new Vue({
      el:'#app',
      methods:{
        showDialog(){
          vm.$alert('错误提示框')
        }
      }
    })

猜你喜欢

转载自blog.csdn.net/weixin_41819098/article/details/88066937