Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Vue itself provides a lot of instructions, but sometimes, we need some special instructions to achieve our specific functions, that needs to customize the instructions, to enrich the functions and features of the component;

How to customize instructions:

Vue.directive(" directive name ",fn);Copy the code

The first argument: the name of the instruction; The second argument is a method that defines the related function of the directive. Note: In the fn function, the first argument is the entire element of the instruction, and vue will pass it in automatically; The second argument is the object corresponding to the instruction; The instruction object contains the basic information of the instruction; Define a stationary instruction as follows:

Vue.directive('pin',function(el,obj){ var pinned = obj.value; // the value passed in the HTML directive if (pinned) {el.style. Position = 'fixed'; el.style.top="20px"; el.style.left="20px"; }else{ el.style.position = 'static'; }});Copy the code

When defining directives, you can use the second parameter of fn to get the corresponding directive value (obj.value), and use the obJ. arg and obJ. modifiers to manipulate elements

  1. Get directive modifiers to manipulate element styles via obj.modifiers
Vue.directive('pin',function(el,obj){ var pinned = obj.value; var position = obj.modifiers; // command decorator if (pinned) {el.style.position = 'fixed'; for(var val in position){ if (position[val]) { el.style[val]='10px'; } } }else{ el.style.position = 'static'; }});Copy the code
  1. Get the parameters of the instruction through obj.arg, and manipulate the element styles according to the parameters

Parameter position:

Instruction: Parameter name <div V-pin :warning=" XXX ">Copy the code
Vue.directive('pin',function(el,obj){ var pinned = obj.value; var position = obj.modifiers; var args = obj.arg; if (pinned) { el.style.position = 'fixed'; if (args=="warning") { el.style.backgroundColor="red"; } for(var val in position){ if (position[val]) { el.style[val]='10px'; } } }else{ el.style.position = 'static'; el.style.backgroundColor=""; }});Copy the code