Home > Web Front-end > Vue.js > body text

8 practical custom instructions in Vue (share)

青灯夜游
Release: 2020-12-21 09:26:33
forward
2153 people have browsed it

8 practical custom instructions in Vue (share)

In Vue, in addition to the default built-in instructions for core functions (v-model and v-show), Vue also allows the registration of custom instructions. Its value lies in when developers need to operate on ordinary DOM elements in certain scenarios.

Related recommendations: "vue.js Tutorial"

Vue custom instructions have two methods: global registration and local registration. Let’s first look at how to register global directives. Register global directives through Vue.directive( id, [definition] ). Then make the Vue.use() call in the entry file.

Batch registration instructions, create a new directives/index.js file

import copy from './copy'
import longpress from './longpress'
// 自定义指令
const directives = {
  copy,
  longpress,
}

export default {
  install(Vue) {
    Object.keys(directives).forEach((key) => {
      Vue.directive(key, directives[key])
    })
  },
}
Copy after login

Introduce and call <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">import Vue from 'vue' import Directives from './JS/directives' Vue.use(Directives)</pre><div class="contentsignin">Copy after login</div></div> in

main.js

The instruction definition function provides several hook functions (optional):

  • bind: only called once, called when the instruction is bound to an element for the first time. You can define a function that is executed once when binding. Initialize action.
  • inserted: Called when the bound element is inserted into the parent node (it can be called as long as the parent node exists, not necessarily in the document).
  • update: Called when the template where the bound element is located is updated, regardless of whether the binding value changes. By comparing the binding values ​​before and after the update.
  • componentUpdated: Called when the template where the bound element is located completes an update cycle.
  • unbind: Called only once, when the instruction is unbound from the element.

Here are some practical Vue custom instructions

  • Copy and paste instructionsv-copy
  • Long press instructionv-longpress
  • Input box anti-shake commandv-debounce
  • No emoticons and special charactersv-emoji
  • Image lazy loadingv-LazyLoad
  • Permission verification instructionsv-premission
  • Implementing page watermarkv-waterMarker
  • Drag and drop commandv-draggable
##v-copy

Requirement: To realize one-click copy of text content, for Right mouse button to paste.

Idea:

    Dynamicly create the
  1. textarea tag, and set the readOnly attribute and move it out of the visible area
  2. will be The copied value is assigned to the
  3. value attribute of the textarea tag and inserted into the body
  4. Selected value
  5. textarea and copied
  6. Remove the
  7. textarea inserted in body
  8. Bind the event when calling for the first time and remove the event when unbinding
  9. const copy = {
      bind(el, { value }) {
        el.$value = value
        el.handler = () => {
          if (!el.$value) {
            // 值为空的时候,给出提示。可根据项目UI仔细设计
            console.log('无复制内容')
            return
          }
          // 动态创建 textarea 标签
          const textarea = document.createElement('textarea')
          // 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
          textarea.readOnly = 'readonly'
          textarea.style.position = 'absolute'
          textarea.style.left = '-9999px'
          // 将要 copy 的值赋给 textarea 标签的 value 属性
          textarea.value = el.$value
          // 将 textarea 插入到 body 中
          document.body.appendChild(textarea)
          // 选中值并复制
          textarea.select()
          const result = document.execCommand('Copy')
          if (result) {
            console.log('复制成功') // 可根据项目UI仔细设计
          }
          document.body.removeChild(textarea)
        }
        // 绑定点击事件,就是所谓的一键 copy 啦
        el.addEventListener('click', el.handler)
      },
      // 当传进来的值更新的时候触发
      componentUpdated(el, { value }) {
        el.$value = value
      },
      // 指令与元素解绑的时候,移除事件绑定
      unbind(el) {
        el.removeEventListener('click', el.handler)
      },
    }
    
    export default copy
    Copy after login
Usage: Add

v-copy and the copied text to Dom

<template>
  <button>复制</button>
</template>

<script> export default {
    data() {
      return {
        copyText: &#39;a copy directives&#39;,
      }
    },
  }
</script>
Copy after login
v-longpress

Requirements: To achieve long Press, the user needs to press and hold the button for a few seconds to trigger the corresponding event

Idea:

    Create a timer and execute the function after 2 seconds
  1. When the user presses the button, the
  2. mousedown event is triggered and the timer is started; when the user releases the button, the mouseout event is called.
  3. If the
  4. mouseup event is triggered within 2 seconds, clear the timer and treat it as an ordinary click event
  5. If the timer is not cleared within 2 seconds, then If it is determined to be a long press, the associated function can be executed.
  6. Consider
  7. touchstart, touchend event on the mobile side
  8. const longpress = {
      bind: function (el, binding, vNode) {
        if (typeof binding.value !== 'function') {
          throw 'callback must be a function'
        }
        // 定义变量
        let pressTimer = null
        // 创建计时器( 2秒后执行函数 )
        let start = (e) => {
          if (e.type === 'click' && e.button !== 0) {
            return
          }
          if (pressTimer === null) {
            pressTimer = setTimeout(() => {
              handler()
            }, 2000)
          }
        }
        // 取消计时器
        let cancel = (e) => {
          if (pressTimer !== null) {
            clearTimeout(pressTimer)
            pressTimer = null
          }
        }
        // 运行函数
        const handler = (e) => {
          binding.value(e)
        }
        // 添加事件监听器
        el.addEventListener('mousedown', start)
        el.addEventListener('touchstart', start)
        // 取消计时器
        el.addEventListener('click', cancel)
        el.addEventListener('mouseout', cancel)
        el.addEventListener('touchend', cancel)
        el.addEventListener('touchcancel', cancel)
      },
      // 当传进来的值更新的时候触发
      componentUpdated(el, { value }) {
        el.$value = value
      },
      // 指令与元素解绑的时候,移除事件绑定
      unbind(el) {
        el.removeEventListener('click', el.handler)
      },
    }
    
    export default longpress
    Copy after login
Use: Add

v-longpress# to Dom ## and the callback function<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">&lt;template&gt;   &lt;button&gt;长按&lt;/button&gt; &lt;/template&gt; &lt;script&gt; export default { methods: { longpress () { alert(&amp;#39;长按指令生效&amp;#39;) } } } &lt;/script&gt;</pre><div class="contentsignin">Copy after login</div></div>v-debounce

Background: During development, some submit and save buttons are sometimes clicked multiple times in a short period of time, which results in multiple Repeated requests to the back-end interface will cause data confusion. For example, if you click the submit button of a new form multiple times, multiple pieces of duplicate data will be added.

Requirements: Prevent the button from being clicked multiple times in a short period of time, and use the anti-shake function to limit clicks to only one time within a specified time.

Idea:

Define a delayed execution method. If the method is called again within the delay time, the execution time will be recalculated.
  1. Bind the time to the click method.
  2. const debounce = {
      inserted: function (el, binding) {
        let timer
        el.addEventListener('keyup', () => {
          if (timer) {
            clearTimeout(timer)
          }
          timer = setTimeout(() => {
            binding.value()
          }, 1000)
        })
      },
    }
    
    export default debounce
    Copy after login
  3. Usage: Add
v-debounce

and callback function to Dom<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">&lt;template&gt;   &lt;button&gt;防抖&lt;/button&gt; &lt;/template&gt; &lt;script&gt; export default { methods: { debounceClick () { console.log(&amp;#39;只触发一次&amp;#39;) } } } &lt;/script&gt;</pre><div class="contentsignin">Copy after login</div></div>v-emoji

Background: Under development The form inputs you encounter often have restrictions on the input content. For example, you cannot enter emoticons and special characters, only numbers or letters, etc.

Our normal method is to handle the

on-change

event of each form. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">&lt;template&gt;   &lt;input&gt; &lt;/template&gt; &lt;script&gt; export default { methods: { vaidateEmoji() { var reg = /[^u4E00-u9FA5|d|a-zA-Z|rns,.?!,。?!…—&amp;$=()-+/*{}[]]|s/g this.note = this.note.replace(reg, &amp;#39;&amp;#39;) }, }, } &lt;/script&gt;</pre><div class="contentsignin">Copy after login</div></div>This code is relatively large and difficult to maintain, so we need to customize a command to solve this problem.

Requirements: Design custom instructions for processing form input rules based on regular expressions. The following takes prohibiting the input of emoticons and special characters as an example.

let findEle = (parent, type) => {
  return parent.tagName.toLowerCase() === type ? parent : parent.querySelector(type)
}

const trigger = (el, type) => {
  const e = document.createEvent('HTMLEvents')
  e.initEvent(type, true, true)
  el.dispatchEvent(e)
}

const emoji = {
  bind: function (el, binding, vnode) {
    // 正则规则可根据需求自定义
    var regRule = /[^u4E00-u9FA5|d|a-zA-Z|rns,.?!,。?!…—&$=()-+/*{}[]]|s/g
    let $inp = findEle(el, 'input')
    el.$inp = $inp
    $inp.handle = function () {
      let val = $inp.value
      $inp.value = val.replace(regRule, '')

      trigger($inp, 'input')
    }
    $inp.addEventListener('keyup', $inp.handle)
  },
  unbind: function (el) {
    el.$inp.removeEventListener('keyup', el.$inp.handle)
  },
}

export default emoji
Copy after login

Usage: Add

v-emoji

to the input box that needs to be verified <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">&lt;template&gt;   &lt;input&gt; &lt;/template&gt;</pre><div class="contentsignin">Copy after login</div></div>v-LazyLoad

Background: In the electronic Commercial projects often have a large number of pictures, such as banner advertising pictures, menu navigation pictures, header pictures of merchant lists such as Meituan, etc. Too many pictures and too large picture sizes often affect the page loading speed and cause a bad user experience, so it is imperative to optimize lazy loading of pictures.

Requirement: Implement a lazy image loading instruction to only load images in the visible area of ​​the browser.

Thinking:

  • 图片懒加载的原理主要是判断当前图片是否到了可视区域这一核心逻辑实现的

  • 拿到所有的图片 Dom ,遍历每个图片判断当前图片是否到了可视区范围内

  • 如果到了就设置图片的 src 属性,否则显示默认图片

图片懒加载有两种方式可以实现,一是绑定 srcoll 事件进行监听,二是使用 IntersectionObserver 判断图片是否到了可视区域,但是有浏览器兼容性问题。

下面封装一个懒加载指令兼容两种方法,判断浏览器是否支持 IntersectionObserver API,如果支持就使用 IntersectionObserver 实现懒加载,否则则使用 srcoll 事件监听 + 节流的方法实现。

const LazyLoad = {
  // install方法
  install(Vue, options) {
    const defaultSrc = options.default
    Vue.directive('lazy', {
      bind(el, binding) {
        LazyLoad.init(el, binding.value, defaultSrc)
      },
      inserted(el) {
        if (IntersectionObserver) {
          LazyLoad.observe(el)
        } else {
          LazyLoad.listenerScroll(el)
        }
      },
    })
  },
  // 初始化
  init(el, val, def) {
    el.setAttribute('src', val)
    el.setAttribute('src', def)
  },
  // 利用IntersectionObserver监听el
  observe(el) {
    var io = new IntersectionObserver((entries) => {
      const realSrc = el.dataset.src
      if (entries[0].isIntersecting) {
        if (realSrc) {
          el.src = realSrc
          el.removeAttribute('src')
        }
      }
    })
    io.observe(el)
  },
  // 监听scroll事件
  listenerScroll(el) {
    const handler = LazyLoad.throttle(LazyLoad.load, 300)
    LazyLoad.load(el)
    window.addEventListener('scroll', () => {
      handler(el)
    })
  },
  // 加载真实图片
  load(el) {
    const windowHeight = document.documentElement.clientHeight
    const elTop = el.getBoundingClientRect().top
    const elBtm = el.getBoundingClientRect().bottom
    const realSrc = el.dataset.src
    if (elTop - windowHeight  0) {
      if (realSrc) {
        el.src = realSrc
        el.removeAttribute('src')
      }
    }
  },
  // 节流
  throttle(fn, delay) {
    let timer
    let prevTime
    return function (...args) {
      const currTime = Date.now()
      const context = this
      if (!prevTime) prevTime = currTime
      clearTimeout(timer)

      if (currTime - prevTime > delay) {
        prevTime = currTime
        fn.apply(context, args)
        clearTimeout(timer)
        return
      }

      timer = setTimeout(function () {
        prevTime = Date.now()
        timer = null
        fn.apply(context, args)
      }, delay)
    }
  },
}

export default LazyLoad
Copy after login

使用,将组件内  标签的 src 换成 v-LazyLoad

<img  alt="8 practical custom instructions in Vue (share)" >
Copy after login

v-permission

背景:在一些后台管理系统,我们可能需要根据用户角色进行一些操作权限的判断,很多时候我们都是粗暴地给一个元素添加 v-if / v-show 来进行显示隐藏,但如果判断条件繁琐且多个地方需要判断,这种方式的代码不仅不优雅而且冗余。针对这种情况,我们可以通过全局自定义指令来处理。

需求:自定义一个权限指令,对需要权限判断的 Dom 进行显示隐藏。

思路:

  1. 自定义一个权限数组
  2. 判断用户的权限是否在这个数组内,如果是则显示,否则则移除 Dom
function checkArray(key) {
  let arr = ['1', '2', '3', '4']
  let index = arr.indexOf(key)
  if (index > -1) {
    return true // 有权限
  } else {
    return false // 无权限
  }
}

const permission = {
  inserted: function (el, binding) {
    let permission = binding.value // 获取到 v-permission的值
    if (permission) {
      let hasPermission = checkArray(permission)
      if (!hasPermission) {
        // 没有权限 移除Dom元素
        el.parentNode && el.parentNode.removeChild(el)
      }
    }
  },
}

export default permission
Copy after login

使用:给 v-permission 赋值判断即可

<div>
  <!-- 显示 -->
  <button>权限按钮1</button>
  <!-- 不显示 -->
  <button>权限按钮2</button>
</div>
Copy after login

vue-waterMarker

需求:给整个页面添加背景水印

思路:

  1. 使用 canvas 特性生成 base64 格式的图片文件,设置其字体大小,颜色等。
  2. 将其设置为背景图片,从而实现页面或组件水印效果
function addWaterMarker(str, parentNode, font, textColor) {
  // 水印文字,父元素,字体,文字颜色
  var can = document.createElement('canvas')
  parentNode.appendChild(can)
  can.width = 200
  can.height = 150
  can.style.display = 'none'
  var cans = can.getContext('2d')
  cans.rotate((-20 * Math.PI) / 180)
  cans.font = font || '16px Microsoft JhengHei'
  cans.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)'
  cans.textAlign = 'left'
  cans.textBaseline = 'Middle'
  cans.fillText(str, can.width / 10, can.height / 2)
  parentNode.style.backgroundImage = 'url(' + can.toDataURL('image/png') + ')'
}

const waterMarker = {
  bind: function (el, binding) {
    addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)
  },
}

export default waterMarker
Copy after login

使用,设置水印文案,颜色,字体大小即可

<template>
  <div></div>
</template>
Copy after login
Copy after login

效果如图所示

8 practical custom instructions in Vue (share)

v-draggable

需求:实现一个拖拽指令,可在页面可视区域任意拖拽元素。

思路:

  • 设置需要拖拽的元素为相对定位,其父元素为绝对定位。

  • 鼠标按下(onmousedown)时记录目标元素当前的 lefttop 值。

  • 鼠标移动(onmousemove)时计算每次移动的横向距离和纵向距离的变化值,并改变元素的 lefttop

  • 鼠标松开(onmouseup)时完成一次拖拽

const draggable = {
  inserted: function (el) {
    el.style.cursor = 'move'
    el.onmousedown = function (e) {
      let disx = e.pageX - el.offsetLeft
      let disy = e.pageY - el.offsetTop
      document.onmousemove = function (e) {
        let x = e.pageX - disx
        let y = e.pageY - disy
        let maxX = document.body.clientWidth - parseInt(window.getComputedStyle(el).width)
        let maxY = document.body.clientHeight - parseInt(window.getComputedStyle(el).height)
        if (x  maxX) {
          x = maxX
        }

        if (y  maxY) {
          y = maxY
        }

        el.style.left = x + 'px'
        el.style.top = y + 'px'
      }
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null
      }
    }
  },
}
export default draggable
Copy after login

使用: 在 Dom 上加上 v-draggable 即可

<template>
  <div></div>
</template>
Copy after login
Copy after login

所有指令源码地址:https://github.com/Michael-lzg/v-directives

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程教学!!

The above is the detailed content of 8 practical custom instructions in Vue (share). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!