search
HomeWeb Front-endVue.js8 practical custom instructions in Vue (share)

8 practical custom instructions in Vue (share)

Dec 21, 2020 am 09:26 AM
javascriptvue.jsfront end

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])
    })
  },
}

Introduce and call <pre class="brush:php;toolbar:false">import Vue from 'vue' import Directives from './JS/directives' Vue.use(Directives)</pre> 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
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>
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
Use: Add

v-longpress# to Dom ## and the callback function<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>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
  3. Usage: Add
v-debounce

and callback function to Dom<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>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. <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>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

Usage: Add

v-emoji

to the input box that needs to be verified <pre class="brush:php;toolbar:false">&lt;template&gt;   &lt;input&gt; &lt;/template&gt;</pre>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

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

<img  src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/image/507/827/655/1608513898590253.png?x-oss-process=image/resize,p_40" class="lazy" alt="8 practical custom instructions in Vue (share)" >

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

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

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

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

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

<template>
  <div></div>
</template>

效果如图所示

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

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

<template>
  <div></div>
</template>

所有指令源码地址: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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Vue.js and the Frontend: A Deep Dive into the FrameworkVue.js and the Frontend: A Deep Dive into the FrameworkApr 22, 2025 am 12:04 AM

Vue.js is loved by developers because it is easy to use and powerful. 1) Its responsive data binding system automatically updates the view. 2) The component system improves the reusability and maintainability of the code. 3) Computing properties and listeners enhance the readability and performance of the code. 4) Using VueDevtools and checking for console errors are common debugging techniques. 5) Performance optimization includes the use of key attributes, computed attributes and keep-alive components. 6) Best practices include clear component naming, the use of single-file components and the rational use of life cycle hooks.

The Power of Vue.js on the Frontend: Key Features and BenefitsThe Power of Vue.js on the Frontend: Key Features and BenefitsApr 21, 2025 am 12:07 AM

Vue.js is a progressive JavaScript framework suitable for building efficient and maintainable front-end applications. Its key features include: 1. Responsive data binding, 2. Component development, 3. Virtual DOM. Through these features, Vue.js simplifies the development process, improves application performance and maintainability, making it very popular in modern web development.

Is vue.js better than React?Is vue.js better than React?Apr 20, 2025 am 12:05 AM

Vue.js and React each have their own advantages and disadvantages, and the choice depends on project requirements and team conditions. 1) Vue.js is suitable for small projects and beginners because of its simplicity and easy to use; 2) React is suitable for large projects and complex UIs because of its rich ecosystem and component design.

Vue.js's Function: Enhancing User Experience on the FrontendVue.js's Function: Enhancing User Experience on the FrontendApr 19, 2025 am 12:13 AM

Vue.js improves user experience through multiple functions: 1. Responsive system realizes real-time data feedback; 2. Component development improves code reusability; 3. VueRouter provides smooth navigation; 4. Dynamic data binding and transition animation enhance interaction effect; 5. Error processing mechanism ensures user feedback; 6. Performance optimization and best practices improve application performance.

Vue.js: Defining Its Role in Web DevelopmentVue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AM

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Understanding Vue.js: Primarily a Frontend FrameworkUnderstanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AM

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix's Frontend: Examples and Applications of React (or Vue)Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AM

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

The Frontend Landscape: How Netflix Approached its ChoicesThe Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AM

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools