vue2插件

插件

插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种:

  1. 添加全局方法或者 property。如:vue-custom-element

  2. 添加全局资源:指令/过滤器/过渡等。如 vue-touch

  3. 通过全局混入来添加一些组件选项。如 vue-router

  4. 添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。

  5. 一个库,提供自己的 API,同时提供上面提到的一个或多个功能。如 vue-router

使用插件

通过全局方法 Vue.use() 使用插件。它需要在你调用 new Vue() 启动应用之前完成:

// 调用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)

new Vue({
  // ...组件选项
})

也可以传入一个可选的选项对象:

Vue.use(MyPlugin, { someOption: true })

Vue.use 会自动阻止多次注册相同插件,届时即使多次调用也只会注册一次该插件。
Vue.js 官方提供的一些插件 (例如 vue-router) 在检测到 Vue 是可访问的全局变量时会自动调用 Vue.use()。然而在像 CommonJS 这样的模块环境中,你应该始终显式地调用 Vue.use():

// 用 Browserify 或 webpack 提供的 CommonJS 模块环境时
var Vue = require('vue')
var VueRouter = require('vue-router')

// 不要忘了调用此方法
Vue.use(VueRouter)

awesome-vue 集合了大量由社区贡献的插件和库。

开发插件

Vue.js 的插件应该暴露一个 install 方法。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:

MyPlugin.install = function (Vue, options) {
  // 1. 添加全局方法或 property
  Vue.myGlobalMethod = function () {
    // 逻辑...
  }

  // 2. 添加全局资源
  Vue.directive('my-directive', {
    bind (el, binding, vnode, oldVnode) {
      // 逻辑...
    }
    ...
  })

  // 3. 注入组件选项
  Vue.mixin({
    created: function () {
      // 逻辑...
    }
    ...
  })

  // 4. 添加实例方法
  Vue.prototype.$myMethod = function (methodOptions) {
    // 逻辑...
  }
}
数字验证码:
import SIdentify from './src/identify'

/* istanbul ignore next */
SIdentify.install = function (Vue) {
  Vue.component(SIdentify.name, SIdentify)
}

export default SIdentify
<template>
  <div class="s-canvas" style="display: flex;">
    <canvas id="s-canvas" :width="contentWidth" :height="contentHeight" @click="getValidCode"></canvas>
  </div>
</template>
<script>
export default {
  name: 'SIdentify',
  props: {
    identifyCode: {
      type: String,
      default: '1234'
    },
    fontSizeMin: {
      type: Number,
      default: 16
    },
    fontSizeMax: {
      type: Number,
      default: 40
    },
    backgroundColorMin: {
      type: Number,
      default: 180
    },
    backgroundColorMax: {
      type: Number,
      default: 240
    },
    colorMin: {
      type: Number,
      default: 50
    },
    colorMax: {
      type: Number,
      default: 160
    },
    lineColorMin: {
      type: Number,
      default: 40
    },
    lineColorMax: {
      type: Number,
      default: 180
    },
    dotColorMin: {
      type: Number,
      default: 0
    },
    dotColorMax: {
      type: Number,
      default: 255
    },
    contentWidth: {
      type: Number,
      default: 153
    },
    contentHeight: {
      type: Number,
      default: 40
    }
  },
  methods: {
    // 生成一个随机数
    randomNum (min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    // 生成一个随机的颜色
    randomColor (min, max) {
      const r = this.randomNum(min, max)
      const g = this.randomNum(min, max)
      const b = this.randomNum(min, max)
      return 'rgb(' + r + ',' + g + ',' + b + ')'
    },
    drawPic () {
      const canvas = document.getElementById('s-canvas')
      const ctx = canvas.getContext('2d')
      ctx.textBaseline = 'bottom'
      // 绘制背景
      ctx.fillStyle = this.randomColor(this.backgroundColorMin, this.backgroundColorMax)
      ctx.fillRect(0, 0, this.contentWidth, this.contentHeight)
      // 绘制文字
      for (let i = 0; i < this.identifyCode.length; i++) {
        this.drawText(ctx, this.identifyCode[i], i)
      }
      this.drawLine(ctx)
      this.drawDot(ctx)
    },
    drawText (ctx, txt, i) {
      ctx.fillStyle = this.randomColor(this.colorMin, this.colorMax)
      ctx.font = this.randomNum(this.fontSizeMin, this.fontSizeMax) + 'px SimHei'
      const x = (i + 1) * (this.contentWidth / (this.identifyCode.length + 1))
      const y = this.randomNum(this.fontSizeMax, this.contentHeight - 5)
      const deg = this.randomNum(-45, 45)
      // 修改坐标原点和旋转角度
      ctx.translate(x, y)
      ctx.rotate(deg * Math.PI / 180)
      ctx.fillText(txt, 0, 0)
      // 恢复坐标原点和旋转角度
      ctx.rotate(-deg * Math.PI / 180)
      ctx.translate(-x, -y)
    },
    drawLine (ctx) {
      // 绘制干扰线
      for (let i = 0; i < 8; i++) {
        ctx.strokeStyle = this.randomColor(this.lineColorMin, this.lineColorMax)
        ctx.beginPath()
        ctx.moveTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
        ctx.lineTo(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight))
        ctx.stroke()
      }
    },
    drawDot (ctx) {
      // 绘制干扰点
      for (let i = 0; i < 100; i++) {
        ctx.fillStyle = this.randomColor(0, 255)
        ctx.beginPath()
        ctx.arc(this.randomNum(0, this.contentWidth), this.randomNum(0, this.contentHeight), 1, 0, 2 * Math.PI)
        ctx.fill()
      }
    },
    getValidCode () {
      this.$emit('getValidCode')
    }
  },
  watch: {
    identifyCode () {
      this.drawPic()
    }
  },
  mounted () {
    this.drawPic()
  }
}
</script>

提示信息

import OperMsg from './components/OperMsg.vue'

const OperTip = {
  install: function (Vue, options = {}) {
    const VueMsg = Vue.extend(OperMsg)
    let msg = null

    const $operTip = {
      show(methodOps = {}) {
        return new Promise(resolve => {
          let defaultNote = '操作成功'
          if (!msg) {
            msg = new VueMsg()
            console.log(msg.$props)
            if (msg.$props.msgType === 'error') {
              defaultNote = '操作失败'
            }
            msg.$props.msgType = methodOps.type || 'success'
            msg.$props.msgContent = methodOps.content || defaultNote
            msg.$mount()
            document.querySelector(options.container || 'body').appendChild(msg.$el)
          }
          if (msg.$props.msgType === 'error') {
            defaultNote = '操作失败'
          }
          msg.$props.msgType = methodOps.type || 'success'
          msg.$props.msgContent = methodOps.content || defaultNote
          msg.show()
          resolve()
        })
      },
      hide() {
        return new Promise(resolve => {
          if (!msg) {
            resolve()
            return
          }
          msg.hide()
        })
      }
    }

    Vue.operTip = Vue.prototype.$operTip = $operTip
    // 注册组件
    Vue.component('operTip', OperMsg)
  }
}

export default OperTip
<template>
  <div class="oper-msg-container"
       ref="msgContainer">
    <transition name="slide">
      <div class="msg"
           v-if="isShowMsg === 'show'"
           :style='{ backgroundColor: color }'>
        <img src="../../../assets/personalCenter/oper-tip-icon.png">
        &nbsp;&nbsp;{{ msgContent.length > 15 ? msgContent.substr(0, 15) + '...' :  msgContent }}
      </div>
    </transition>
  </div>
</template>
<script>
export default {
  name: 'OperMsg',
  props: {
    msgType: {
      type: String,
      default: 'success'
    },
    msgContent: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      isShowMsg: 'hide',
      timer: null,
      clearHeightTimer: null,
      color: '#FFA300'
    }
  },
  mounted () {
  },
  watch: {
    isShowMsg (oldVal, newVal) {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (newVal === 'hide') {
        this.timer = setTimeout(() => {
          this.hide()
        }, 3000)
      }
    }
  },
  methods: {
    show () {
      console.log(this.msgType)
      if (this.msgType === 'error') {
        this.color = '#ED6355'
      } else {
        this.color = '#FFA300'
      }
      this.isShowMsg = 'show'
    },
    hide () {
      this.isShowMsg = 'hide'
    }
  }
}
</script>
<style lang="scss" scoped>
.oper-msg-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 10000;
  position: fixed;
  top: 5px;
  top: calc(5px + constant(safe-area-inset-top));
  top: calc(5px + env(safe-area-inset-top));
  background: transparent;
  .msg {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10px 30px;
    font-size: 14px;
    font-weight: 500;
    color: rgba(255, 255, 255, 1);
    line-height: 14px;
    // background: rgba(255,163,0,1);
    border-radius: 20px;
    img {
      width: 20px;
      height: 20px;
    }
  }
  .slide-enter-active {
    animation: slideInDown 0.5s;
  }
  .slide-leave-active {
    animation: slideOutUp 0.5s;
  }
  @-webkit-keyframes slideInDown {
    from {
      -webkit-transform: translate3d(0, -100%, 0);
      transform: translate3d(0, -100%, 0);
      visibility: visible;
    }
    to {
      -webkit-transform: translate3d(0, 0, 0);
      transform: translate3d(0, 0, 0);
    }
  }
  @-webkit-keyframes slideOutUp {
    from {
      -webkit-transform: translate3d(0, 0, 0);
      transform: translate3d(0, 0, 0);
    }
    to {
      visibility: hidden;
      -webkit-transform: translate3d(0, -100%, 0);
      transform: translate3d(0, -100%, 0);
    }
  }
}
</style>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、UI组件及框架 element - 饿了么出品的Vue2的web UI工具套件 mint-ui - Vue 2...
    站着瞌睡阅读 4,421评论 0 3
  • 插件 插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种: 添加全局方法或者 p...
    莫伊剑客阅读 1,924评论 0 0
  • plugin 的作用 插件通常用来为 Vue 添加全局功能。插件的功能范围没有严格的限制——一般有下面几种: 添加...
    樱桃小白菜阅读 910评论 0 0
  • 1. 简介 本节我们将介绍 Vue 的插件。包括什么是插件、如何使用插件、如何编写一个简单的插件。其中,编写和使用...
    木子教程阅读 2,490评论 0 1
  • 一、本质 造轮子,给Vue生态圈提供更多优良的插件或工具 插件通常用来为 Vue 添加全局功能。插件的功能范围没有...
    MonkeyCode阅读 877评论 0 0