Home >Web Front-end >Vue.js >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
The instruction definition function provides several hook functions (optional):
Here are some practical Vue custom instructions
v-copy
v-longpress
v-debounce
v-emoji
v-LazyLoad
v-premission
v-waterMarker
v-draggable
tag, and set the
readOnly attribute and move it out of the visible area
attribute of the
textarea tag and inserted into the
body
and copied
inserted in
body
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
v-copy and the copied text to Dom
<template> <button>复制</button> </template> <script> export default { data() { return { copyText: 'a copy directives', } }, } </script>v-longpressRequirements: To achieve long Press, the user needs to press and hold the button for a few seconds to trigger the corresponding eventIdea:
event is triggered and the timer is started; when the user releases the button, the
mouseout event is called.
event is triggered within 2 seconds, clear the timer and treat it as an ordinary click event
,
touchend event on the mobile side
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
v-longpress# to Dom ## and the callback function<pre class="brush:php;toolbar:false"><template>
<button>长按</button>
</template>
<script>
export default {
methods: {
longpress () {
alert(&#39;长按指令生效&#39;)
}
}
}
</script></pre>
v-debounce
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.const debounce = { inserted: function (el, binding) { let timer el.addEventListener('keyup', () => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { binding.value() }, 1000) }) }, } export default debounce
and callback function to Dom<pre class="brush:php;toolbar:false"><template>
<button>防抖</button>
</template>
<script>
export default {
methods: {
debounceClick () {
console.log(&#39;只触发一次&#39;)
}
}
}
</script></pre>
v-emoji
Our normal method is to handle the
on-change event of each form. <pre class="brush:php;toolbar:false"><template>
<input>
</template>
<script> export default {
methods: {
vaidateEmoji() {
var reg = /[^u4E00-u9FA5|d|a-zA-Z|rns,.?!,。?!…—&$=()-+/*{}[]]|s/g
this.note = this.note.replace(reg, &#39;&#39;)
},
},
} </script></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"><template>
<input>
</template></pre>
v-LazyLoad
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 alt="8 practical custom instructions in Vue (share)" >
背景:在一些后台管理系统,我们可能需要根据用户角色进行一些操作权限的判断,很多时候我们都是粗暴地给一个元素添加 v-if / v-show
来进行显示隐藏,但如果判断条件繁琐且多个地方需要判断,这种方式的代码不仅不优雅而且冗余。针对这种情况,我们可以通过全局自定义指令来处理。
需求:自定义一个权限指令,对需要权限判断的 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>
需求:给整个页面添加背景水印
思路:
canvas
特性生成 base64
格式的图片文件,设置其字体大小,颜色等。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>
效果如图所示
需求:实现一个拖拽指令,可在页面可视区域任意拖拽元素。
思路:
设置需要拖拽的元素为相对定位,其父元素为绝对定位。
鼠标按下(onmousedown)
时记录目标元素当前的 left
和 top
值。
鼠标移动(onmousemove)
时计算每次移动的横向距离和纵向距离的变化值,并改变元素的 left
和 top
值
鼠标松开(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
相关推荐:
更多编程相关知识,请访问:编程教学!!
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!