Vue. directive custom commands
Many tutorials focus on the concepts and syntaxes of custom commands. This document does not focus on syntax and concepts, but on usage.
Custom commands are basically used to operate the DOM. Although the data-driven view is officially recommended, sometimes you still need custom commands to operate the DOM and the commands can be reused.
1. Drag custom commands
HTML:
<Div v-drag> I can drag and drop </div>
JS:
Vue. directive ('drag', inserted: function (el) {// inserted hook function: triggered when an element is inserted with the parent element, let oDiv = el can be omitted; // el --> trigger the DOM element oDiv. onmousedown = function (e) {let l = e. clientX-oDiv.offsetLeft; let t = e. clientY-oDiv.offsetTop; document. onmousemove = function (e) {oDiv. style. left = e. clientX-l + 'px '; oDiv. style. top = e. clientY-t + 'px ';}; oDiv. onmouseup = function () {document. onmousemove = null; oDiv. onmouseup = null ;}}})
Custom commands can also be used to introduce third-party plug-ins. Previously, JQuery was used to build projects.
The advantage of custom commands is that no matter what JQuery was previously written or whether it was native js, they can be directly encapsulated into custom commands without rewriting.
For example, drag:
Drag. js:
export default function(el){ let oDiv=el; oDiv.onmousedown=function(e){ let l=e.clientX-oDiv.offsetLeft; let t=e.clientY-oDiv.offsetTop; document.onmousemove=function(e){ oDiv.style.left=e.clientX-l+'px'; oDiv.style.top=e.clientY-t+'px'; }; oDiv.onmouseup=function(){ document.onmousemove=null; oDiv.onmouseup=null; } }}
Vue:
import drag from 'drag.js'Vue.directive('drag',drag)
HTML:
<Div v-drag> I can drag and drop </div>
2. image loading
A random color placeholder is used when the image is not loaded during the loading process. After the image is loaded, it is displayed directly. You can use custom commands to complete the process.
HTML:
</img> // The url data () {url: 'src/assets/logo.png '} cannot be entered directly '}
Vue:
Vue. directive ('imgurl', function (el, binding) {var color = Math. floor (Math. random () * 1000000); // set random color el. style. backgroundColor = '#' + color; var img = new Image (); img. src = binding. value; // --> binding. value refers to the img parameter after the instruction. onload = function () {el. style. backgroundColor = ''; el. src = binding. value ;}})
Lodash. js tool library can be used
More vue APIs --> GO
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.