zoukankan      html  css  js  c++  java
  • Vue开发插件的简单步骤

    为了每次总是可以重复使用自己写的组件,就把它改成插件。

    传送门:https://www.cnblogs.com/linxin/p/6637904.html

    案例是从这里学习的。但用法跟直接引入mint-ui这些有些不同。

    Vue插件开发方法(官网):https://cn.vuejs.org/v2/guide/plugins.html#开发插件

    toast.js代码:

    var Toast = {}
    Toast.install = function (Vue, options) {
      // 默认参数,defaultType:toast的位置;duration:持续多少时间消失
      let opt = {
        defaultType: 'bottom',
        duration:'1000'
      }
      // 将Vue.use({})里面的参数重新赋值给opt
      for(let property in options){
        opt[property] = options[property];
        console.log(opt[property])
      }
      // 调用的时候直接 this.$toast调用该插件
      Vue.prototype.$toast = (tips, type) => {
        // toast的位置,该位置的CSS写在了toast.css
        if(type){
          opt.defaultType = type;
        }
        // 只允许一个toast存在
        if(document.getElementsByClassName('vue-toast').length){
          return;
        }
        let toastTpl = Vue.extend({
          // toast的html模板
          template: '<div class="vue-toast toast-'+opt.defaultType+'">' + tips + '</div>'
        })
        // 将该toast手动挂载到$el
        let tpl = new toastTpl().$mount().$el;
    
        document.body.appendChild(tpl);
        setTimeout(function () {
          // 持续多少时间后,将toast移除
          document.body.removeChild(tpl);
        },opt.duration);
      }
      // 通过this.$toast.bottom() 调用组件,直接显示位置
      ['bottom', 'center', 'top'].forEach(type => {
        Vue.prototype.$toast[type] = (tips) => {
          return Vue.prototype.$toast(tips, type)
        }
      })
    }
    // 导出toast,让需要的地方去import
    export default Toast;

    toast.css

    .vue-toast {
      border:1px solid #e6e6e6;
      box-shadow:2px 2px 1px #e6e6e6;
      border-radius: 4px;
      padding: 10px 50px;
      position: absolute;
      z-index: 1000;
      color:#fff;
      left:50%;
      transform: translateX(-50%);
    }
    .toast-top {
      top:0;
    }
    .toast-bottom {
      bottom:0;
    }
    .toast-center {
      top:50%;
      transform: translate(-50%,-50%);
    }

    在main.js引入该插件

    // 引入CSS
    import './components/toast/toast.css'
    // 引入toast.js
    import Toast from './components/toast/toast'
    // 引用Toast组件,并配置持续时间的参数,这里如果添加了{},
    // 则默认参数跟着改变
    Vue.use(Toast,{duration:2000})

    最后,调用了,在要使用该组件的地方,调用

     mounted(){
        this.$toast.center('loading');
      }

    最终成果:刷新了一下页面,就显示出来,2ms后就消失。

  • 相关阅读:
    NFC Basics(基本NFC)——翻译自developer.android.com
    【LeetCode】Sort Colors 解题报告
    发送手机物理标识请求
    Java编程介绍
    emacs 中使用git diff命令行
    OpenJudge百炼习题解答(C++)--题4074:积水量
    编程之美2.9 斐波那契数列
    Application Architecture Determines Application Performance
    程序包javax.servlet.annotation不存在
    mysql 严格模式 Strict Mode说明
  • 原文地址:https://www.cnblogs.com/xiaoxiaossrs/p/8509973.html
Copyright © 2011-2022 走看看