Customization and use of Vue global instructions and private instructions

1. Customize global instructions

Open the door and raise a chestnut:

<label>
    搜索
    <input type="text" id="search">
</label>

At this time, to get the focus event of this input box in the native method is like this:

document.getElementById("search").focus();

In Vue, use custom instructions to achieve this effect. The
instructions are like v-model v-text, but these are provided by Vue by default,
and the custom instructions are customized ( nonsense)

All instructions in Vue v-start with

Customize a custom command called v-focus:
add to the label

<label>
    搜索
    <input type="text" id="search" v-focus>
</label>

Then use Vue.directive () to define the global instruction.
Syntax: The Vue.directive(指令名称,对象)
first parameter is the name of the instruction. When the instruction is defined, it does not need to be prefixed with v-, but the
second parameter must be added when calling. It is an object. There are some instruction-related hook functions that can perform related operations at specific stages

The first parameter in each hook function is always el, which means that the element to which the instruction is bound ( el ement) [Of course, the parameter name can be taken at will]
It is a native js dom object, so it can be used on it js method

Commonly used hook functions are bind inserted and updated:

  • bind it will execute the bind function immediately whenever an instruction on the elements bound to
    it only once because of a command element can be bound to a time
  • inserted when the element into the DOM when inserted performs the function
    it is also only once
  • updated is when the DOM node (VNode component) is updated, the upload function will be executed and
    may be triggered multiple times
Vue.directive("focus",{
            // 钩子函数
            
            // 在bind刚绑定的时候 元素还并没有被放到dom中去 因此此时调用focus()方法没作用 不会生效 因为一个元素只有在插入dom之后才能获取焦点
            bind:function(el)
            {
                // el.focus();
            },
            
            // 元素插入到DOM中的时候会执行该inserted函数
            // 【只会执行一次】
            inserted:function(el)
            {
                el.focus();
            },
            
            // 当DOM节点(VNode组件)更新的时候 会执行该upload函数
            // 【可能会触发多次】
            updated:function(el)
            {
            
            }
        })

Besides that:

  • componentUpdated: the DOM node (VNode component) of the component where the instruction is located and its child DOM nodes (VNode component) are updated after all
  • unbind: called
    only when the instruction and element are unbound

So you can implement custom instructions


Of course, there is a difference between style and behavior: what
is style? The style is like setting colors
and the behavior is like js behavior like focus ()

Take the custom font color instruction as a chestnut:

Vue.directive("color",{
            bind:function(el)
            {
                el.style.color="aqua";
            }
        })

We found that the style can be set in bind.
That's because as long as the style is parsed, it will have a color
style displayed on the page. As long as it is bound to the element through the instruction, no matter whether the element is inserted into the page. The element will definitely have an inline style.
After that, the element will definitely be displayed on the page. At this time, the browser's rendering engine will parse the style and apply it to the element.

But a method like focus () is an action. The action must be added to the DOM to get the focus. When bind, it is only in memory and not added to the DOM.
The behavior called in memory is then naturally rendered on the page. Invalid
and insert is only called after reaching the page so the behavior will be effective

In short, operations related to js behavior are best performed in inserted to prevent js behavior from taking effect
, and style-related operations can usually be performed in bind


Get the passed value in the custom instruction

Add quotation marks at the time of definition because a string is passed.
Without quotation marks, it will be recognized as a variable

<input type="text" id="search" v-color="'blue'">

First look at the parameters shared by the hook function:

  • el: The element bound by the instruction can be used to directly manipulate the DOM
  • binding: An object contains the following attributes:
    name : the name of the instruction (excluding the v-prefix)
    value : the binding value
    of the instruction Example: the binding value in v-my-directive = "1 + 1" is 2 ie: value is The result after string parsing
    oldValue: the previous value bound by the instruction is
    only available in the update and componentUpdated hooks. It can be used
    regardless of whether the value changes.
    Expression : Instruction expression in string form
    Example: in v-my-directive = "1 The expression in "+1" is "1 + 1", that is: expression is the original result without string parsing
    arg : the parameter passed to the instruction
    Example: the parameter is "foo" in v-my-directive: foo
    modifiers : An object containing modifiers. For example: in v-my-directive.foo.bar, the modifier object is {foo: true, bar: true}
  • vnode: Virtual node generated by Vue compilation
  • oldVnode: The last virtual node
    is only available in the update and componentUpdated hooks

Insert picture description here
Get the passed value
Example:

// 自定义设置字体颜色指令
Vue.directive("color",{
    bind:function(el,binding) // 此处的el和binding可任意命名
    {
        console.log(binding.value);
        el.style.color=binding.value;
    }
})

Second, custom private instructions

Just like filters, there are not only common commands but also private commands.
Custom private commands are similar to custom private filters. They
are set in the property object of the Vue instance.

<div id="app2">
	<h3 v-fontWeight="1000">{{date | dateFormat}}</h3>
</div>
<script>
	var vm2=new Vue({
	            el:'#app2',
	            data:{
	                date:new Date()
	            },
	            methods:{},
	            filters:{},
	            // 自定义私有指令
	            directives:{
	                "fontweight":{
	                    bind:function(el,binding)
	                    {
	                        el.style.fontWeight=binding.value;
	                    }
	                }
	            }
	        })
</script>

Third, the abbreviation of the instruction

Vue's custom commands also support shorthand

If you only want to bindand updateaction on these two hooks for repeated
and does not care about the other hook function

Then you can follow the method directly after the instruction name

Example:

<div id="app2">
	<h3 v-fontWeight="1000" v-fontsize="'50'">{{date | dateFormat}}</h3>
</div>
<script>
	var vm2=new Vue({
	            el:'#app2',
	            data:{
	                date:new Date()
	            },
	            methods:{},
	            filters:{},
	            // 自定义私有指令
	            directives:{
	                // 字体粗细
	                "fontweight":{
	                    bind:function(el,binding)
	                    {
	                        el.style.fontWeight=binding.value;
	                    }
	                },
	                // 字体大小
	                "fontsize":function(el,binding) // 该function就相当于将里面的代码写到【且只写到】bind和update钩子上去了
	                {
	                    el.style.fontSize=parseInt(binding.value)+"px";
	                }
	            }
	        })
</script>

Published 200 original articles · praised 11 · 730,000 views

Guess you like

Origin blog.csdn.net/Piconjo/article/details/105606565