current position:Home>Vue - 09-01 custom instruction

Vue - 09-01 custom instruction

2022-01-27 01:26:51 Nanchen_ forty-two

Except for some Vue The core instructions included in (v-model as well as v-show) outside ,Vue You can also customize the registration instructions

You can use directives Option to register instructions

The following will be used globally and locally v-focus, To achieve the function of automatically getting the focus when the page is loaded

It's just... Here inserted and el Parameters That is to say  

The first global writing method :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <title>Document</title>
</head>
<body>
    <div id="app">
        <p> When the page loads ,input Element gets focus automatically :</p>
        <input type="text" v-focus>
    </div>
    <script>
        Vue.directive('focus', {
            inserted(el) {
                el.focus()
            }
        });
        const app = new Vue({
            el:"#app",
        })
    </script>
</body>
</html>

The second local writing :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <title> Local writing </title>
</head>
<body>
    <div id="app">
        <p> When the page loads ,input Element gets focus automatically :</p>
        <input type="text" v-focus>
    </div>
    <script>
        const app = new Vue({
            el:"#app",
            methods:{

            },
            //  Be careful : Here plus s, There is no need to add... In global writing s
            directives:{
                focus:{
                    inserted(el){
                        el.focus();
                    }
                }
            }
        })
    </script>
</body>
</html>

The instruction definition function provides several hook functions ( Optional ):

bind: Call it once , The first time an instruction is bound to an element , With this hook function, you can define an initialization action to be executed once during binding .

inserted: Called when the bound element is inserted into the parent node ( If the parent node exists, you can call , It doesn't have to exist in document in ).

update: Called when the template of the bound element is updated , Regardless of whether the binding value changes . By comparing the binding values before and after the update , Unnecessary template updates can be ignored ( See the following for detailed hook function parameters ).

componentUpdated: Called when the template of the bound element completes an update cycle .

unbind: Call it once , Call when an instruction is unbound from an element .

The parameters of the hook function are :

  • el: Element bound by instruction , Can be used for direct operation DOM .
  • binding: An object , Contains the following properties :
    • name: Instruction name , barring  v-  Prefix .
    • value: Binding value of instruction , for example : v-my-directive="1 + 1", value The value of is  2.
    • oldValue: Previous value of instruction binding , Only in  update  and  componentUpdated  Available in hook . Available regardless of value change .
    • expression: The expression or variable name of the bound value . for example  v-my-directive="1 + 1" , expression The value of is  "1 + 1".
    • arg: Parameters passed to the instruction . for example  v-my-directive:foo, arg The value of is  "foo".
    • modifiers: An object with modifiers . for example : v-my-directive.foo.bar, Modifier object modifiers The value of is  { foo: true, bar: true }.
  • vnode: Vue Compile generated virtual nodes .
  • oldVnode: Previous virtual node , Only in  update  and  componentUpdated  Available in hook .

Understand the relevant parameters of user-defined instructions , Here is what can be used , Look at the code below

The effect is shown below :

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title> Understand the relevant parameters of user-defined instructions </title>
		<script src="https://cdn.jsdelivr.net/npm/vue"></script>
	</head>
	<body>
		<div id="app" v-num:hello.a.b="message">
			
		</div>
		<script type="text/javascript">
		Vue.directive('num',{
			bind(el,binding){
				var s= JSON.stringify;
				el.innerHTML = 
				'name:' + s(binding.name)+'<br>'+
				'value' + s(binding.value) + '<br>' +
				"expression"+s(binding.expression) +'<br>'+
				"arg"+ s(binding.arg)+'<br>'+
				'modifiers'+s(binding.modifiers)+'<br>'
			}
		})
			const vm = new Vue({
				el:'#app',
				data(){
					return{
						message:' Hello '
					}
				},
			})
		</script>
	</body>
</html>

 

  commonly binging These five methods will be used

  There is no need to simplify other hook functions :

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://cdn.jsdelivr.net/npm/vue"></script>
	</head>
	<body>
		<div id="app" v-num="{color:'gray',text:'NanChen'}">
			<!--  I just want to set up message The color of the value can be used without the hook function , Directly abbreviate  -->
		</div>
		<script type="text/javascript">
		Vue.directive('num',function(el,binging){
				console.log(el);
				console.log(binging.value);
				//  Give the obtained text to el And show it 
			el.innerHTML = binging.value.text
			//  Pass the obtained color to el style 
			el.style.backgroundColor =  binging.value.color
		})
			const vm = new Vue({
				el:'#app',
			})
		</script>
	</body>
</html>

The effect is as follows : 

Of course, you can also write multiple custom instructions :

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://cdn.jsdelivr.net/npm/vue"></script>
	</head>
	<body>
		<!--  In the custom instruction, if it is an object, use value To display the value , If it's a variable, use expression -->
		<div id="app" v-num="{color:'gray',text:'NanChen'}" v-num2="message">
			<!--  I just want to set up message The color of the value can be used without the hook function , Directly abbreviate  -->
		</div>
		<script type="text/javascript">
		
		Vue.directive('num',function(el,binging){
				console.log(el);
				console.log(binging.value);
				//  Give the obtained text to el And show it 
			el.innerHTML = binging.value.text
			//  Pass the obtained color to el style 
			el.style.backgroundColor =  binging.value.color
		})
			const vm = new Vue({
				el:'#app',
				methods:{
					message:' welcome !'
				},
				directives:{
					num2:{
						inserted:function(el,binging){
							console.log(el);
							console.log(binging.expression);
							el.innerHTML = binging.expression
						}
					}
				}
			})
		</script>
	</body>
</html>

effect :( In front of here el.innerHTML Will be covered ) 

copyright notice
author[Nanchen_ forty-two],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270126488940.html

Random recommended