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 <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
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 instructions
v-copy
- Long press instruction
v-longpress
- Input box anti-shake command
v-debounce
- No emoticons and special characters
v-emoji
- Image lazy loading
v-LazyLoad
- Permission verification instructions
v-premission
- Implementing page watermark
v-waterMarker
- Drag and drop command
v-draggable
- Dynamicly create the
- textarea
tag, and set the
readOnlyattribute and move it out of the visible area
will be The copied value is assigned to the - value
attribute of the
textareatag and inserted into the
body Selected value - textarea
and copied
Remove the - textarea
inserted in
body Bind the event when calling for the first time and remove the event when unbinding -
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
v-copy and the copied text to Dom
<template> <button>复制</button> </template> <script> export default { data() { return { copyText: 'a copy directives', } }, } </script>
- Create a timer and execute the function after 2 seconds
- When the user presses the button, the
- mousedown
event is triggered and the timer is started; when the user releases the button, the
mouseoutevent is called.
If the - mouseup
event is triggered within 2 seconds, clear the timer and treat it as an ordinary click event
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. - Consider
- touchstart
,
touchendevent 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<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><template>
<button>长按</button>
</template>
<script>
export default {
methods: {
longpress () {
alert(&#39;长按指令生效&#39;)
}
}
}
</script></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.- Bind the time to the click method.
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 loginUsage: Add
and callback function to Dom<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false"><template>
<button>防抖</button>
</template>
<script>
export default {
methods: {
debounceClick () {
console.log(&#39;只触发一次&#39;)
}
}
}
</script></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"><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><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
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"><template>
<input>
</template></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
使用,将组件内 标签的 src
换成 v-LazyLoad
<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/507/827/655/1608513898590253.png" class="lazy" alt="8 practical custom instructions in Vue (share)" >
v-permission
背景:在一些后台管理系统,我们可能需要根据用户角色进行一些操作权限的判断,很多时候我们都是粗暴地给一个元素添加 v-if / v-show
来进行显示隐藏,但如果判断条件繁琐且多个地方需要判断,这种方式的代码不仅不优雅而且冗余。针对这种情况,我们可以通过全局自定义指令来处理。
需求:自定义一个权限指令,对需要权限判断的 Dom 进行显示隐藏。
思路:
- 自定义一个权限数组
- 判断用户的权限是否在这个数组内,如果是则显示,否则则移除 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
需求:给整个页面添加背景水印
思路:
- 使用
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>
效果如图所示
v-draggable
需求:实现一个拖拽指令,可在页面可视区域任意拖拽元素。
思路:
设置需要拖拽的元素为相对定位,其父元素为绝对定位。
鼠标按下
(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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

Combination of Golang and front-end technology: To explore how Golang plays a role in the front-end field, specific code examples are needed. With the rapid development of the Internet and mobile applications, front-end technology has become increasingly important. In this field, Golang, as a powerful back-end programming language, can also play an important role. This article will explore how Golang is combined with front-end technology and demonstrate its potential in the front-end field through specific code examples. The role of Golang in the front-end field is as an efficient, concise and easy-to-learn

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
