Vue.js from entry to practice study notes (2) - instructions

Vue.js from entry to practice study notes (2) - instructions


Directives are special attributes prefixed with v- whose value is restricted to a single expression. The role of the directive is to apply its associated effects to the DOM when the value of the expression changes.

1. Built-in instructions

For some commonly used page functions, it provides the use form encapsulated by instructions and uses them in the form of HTML element attributes.

1. v-show (display or not)

The v-show directive shows or hides HTML elements based on the true or false value of an expression. Using the v-show command, the element itself is to be rendered, and whether the element is displayed is controlled by setting the CSS style property display.
When the value is false, it is equivalent to setting the style:

    style="display:none"

How to show or hide multiple elements?

Use the new <template>elements of HTML5 to wrap multiple elements that need to be switched between display and hiding, and then <template>use the v-show command on the elements. The final rendering result will not contain the element, and the element is treated as an invisible wrapping element, which is mainly used for conditional judgment of grouping and list rendering.

	<template v-show="isShow">
		<form>
			<p>template里用v-show指令</p>
			<p>template里用v-show指令</p>
		</form>
	</template>

2. v-if/v-else-if/v-else (conditional judgment)

v-if directive

Generate or delete an element according to the true or false value of the expression (the same effect as v-show, but the implementation mechanism is different)

The implementation mechanism of the v-if instruction is different from the v-show instruction in terms of whether the HTML element is displayed or not:
when the value of the expression is false, the v-if instruction will not create the element, and only when it is true, the element will actually be created Element;
and the v-show command regardless of the value of the expression is true or false, the element will be created, and whether it is displayed or not is controlled by the CSS style property display.

v-if controls the creation or deletion of multiple elements, and also <template>wraps multiple elements with elements.

v-if vs. v-show

  • v-if has higher switching overhead, if the operating conditions rarely change, it is better to use v-if;
  • v-show has a higher initial rendering overhead, if you need to frequently switch the display or hide of elements, it is better to use v-show.

The v-else-if and v-else instructions are used together with v-if to achieve mutual exclusion condition judgment:

  • When a condition is met, subsequent conditions will not be judged.
  • v-else-if, v-else should follow immediately after v-if or v-else-if.

Manage reusable elements with keys

Vue renders elements as efficiently as possible, usually reusing existing elements instead of rendering from scratch, which makes rendering efficient.

For example, if the same <input>element is used in two templates, Vue will reuse <input>the element in order to improve rendering efficiency, so that when switching, <input>the content will not be replaced, only its placeholder attribute will be replaced.

If you don't want to reuse, you can tell Vue, "These two elements are completely independent, don't reuse them" by adding a key attribute with a unique value to the element.

	<input placeholder="请输入你的用户名" key="username-input">
	<input placeholder="请输入你的邮箱" key="email-input">

3. v-for (loop)

The v-for command renders a list by looping, and the looping object can be an array or a JavaScript object.

v-for iterates through the array

Expression syntax: item in items, where items is the source data array, and item is the alias of the array element being iterated.

in <html>,

	<li v-for="book in books">{
    
    {
    
    book.title}}</li>

In <script>, an array property books is defined in the data object of the Vue instance:

	data:{
    
    
		books:[
			{
    
    title:'vue'},
			{
    
    title:'123'},
			{
    
    title:'java'}
		]
	}

book is the alias of the element in the array, and the value of book is reset to the value of the current index of the array every time it is looped. Inside the <li>element, the variable can be referenced through Mustache syntax.

Tip: The expression of the v-for instruction can also use of instead of in as a separator, which is closer to the syntax of JavaScript iterators, such as

	<li v-for="book of books">{
    
    {
    
    book.title}}</li>

Supports an optional parameter as the index of the current item

	<li v-for="(book, index) in books">{
    
    {
    
    index}} - {
    
    {
    
    book.title}}</li>    //多个参数需要放在圆括号里

Array update detection

The core of Vue is the two-way binding between view and data, in order to monitor the changes of elements in the array, so that the changes can be reflected in the view in time. Vue wraps the following mutation methods for arrays:

	push()
	pop()    
	shift()
	unshift()    //数组的unshift()方法,该方法向数组的开头添加一个或多个元素
	splice()
	sort()
	reverse()
	//如:
	vm.books.push({
    
    title:'java web'})    //新增一条数据在数组末尾

There are also some non-mutating methods in the array, such as: filter(), concat(), slice(), which will not change the original data. Instead, a new array is returned. If you want to update the view automatically, you can replace the original array with the new array. like:

	vm.books = vm.books.concat({
    
    title:'java web'})     //使用新数组替换原数组,同步视图更新

When Vue detects an array change, it will not re-render the entire list, but maximize the reuse of DOM elements. Therefore, items with the same element in the replaced array will not be re-rendered. The new array replaces the old array without worrying about performance issues.

Note 1, how to directly set the data item through the index: (the effect is similar to vm.books[0]={...})

	Vue.set(vm.books,  0, {
    
    title:'java web'})    //使用Vue全局set()方法
	vm.books.splice(0, 1, {
    
    title:'java web'})    //使用数组原型的splice()方法
	vm.set(vm.books,  0, {
    
    title:'java web'})    //使用Vue实例的set()方法,该方法是Vue.set的一个别名。

Note 2, how to modify the length of the array: (the effect is similar to vm.books.length = 1)

	vm.books.splice(1)

filter and sort

Sometimes it is desirable to display a filtered or sorted version of an array without actually changing or resetting the original data. In this case, create a computed property that returns the filtered or sorted array.

	<li v-for="n in evenNumbers">{
    
    {
    
    n}}</li> 
	......
	
	data:{
    
    
		numbers:[1,2,3,4,5]
	},
	computed:{
    
     
		evenNumbers: function(){
    
      
			return this.numbers.filter(fuction(number){
    
    
				return number % 2 == 0
			})
		}
	}

In cases where computed properties don't fit, like in nested v-for loops, it's also possible to:

	<li v-for="n in even(numbers)">{
    
    {
    
    n}}</li>
	......
	
	data:{
    
    
		numbers:[1,2,3,4,5]
	}, 
	methods:{
    
     
		even: function(numbers){
    
      
			return numbers.filter(fuction(number){
    
    
				return number % 2 == 0
			})
		}
	}

iterate over integers

The v-for directive can accept integers. In this case, the template will be repeated the corresponding number of times when rendering.

	<div>
		<--遍历110-->
		<span v-for="n in 10">{
    
    {
    
    n}}</span>
	</div>    

The output is: 1 2 3 4 5 6 7 8 9 10

v-for traverses objects

The syntax of traversing objects is the same as that of traversing arrays, that is, value in object, where object is the object to be iterated, and value is the alias of the property of the iterated object.

	<li v-for="value in book">{
    
    {
    
    value}}</li>
	data:{
    
    
		book:{
    
    
			title:'vc++',
			author:'sun',
			isbn:'123232'
		}
	}

If you want to get the property name of the object, you can use the optional property name parameter (key name) as the second parameter.

	<li v-for="(value, key) in book">{
    
    {
    
    key}} : {
    
    {
    
    value}}</li>  

You can also use the third parameter as an index

	<li v-for="(value, key, index) in book">{
    
    {
    
    index}}.{
    
    {
    
    key}} : {
    
    {
    
    value}}</li>  

Object update detection

Due to JavaScript limitations, Vue cannot detect the addition and removal of object properties. You can use Vue's global set() and delete() methods to add and remove properties and trigger view updates.

	Vue.set(vm.book,  'pulishdate', '2019-06-01')    //使用Vue全局set()方法添加属性
	vm.set(vm.book,   'pulishdate', '2019-06-01')    //使用Vue实例的set()方法添加属性
	Vue.delete(vm.book,  'isbn')    //使用Vue全局delete()方法删除属性
	vm.delete(vm.book,   'isbn')    //使用Vue实例的delete()方法删除属性

<temple>Use v-for on

Like v-show and v-if, you can render a piece of content that contains multiple elements.

<template v-for="item in items"><li>{
    
    {
    
    item.msg}}</li><li>{
    
    {
    
    item.code}}</li></template>

key attribute (used to remind Vue to track changed elements)

When Vue is updating a list of elements rendered with v-for, it uses the "in-place update" strategy by default. If the order of the data items is changed, Vue will not move the DOM elements to match the order of the data items, but will update each element in place and make sure they render correctly at each index position.
When checked, the instruction remembers to check the subscript 0 of the array. After adding a new element, although the length of the array changes, it still remembers to check the data with subscript 0, and a problem occurs.
In order to give Vue hints to track the identity of each node so that existing elements can be reused and reordered, a unique key attribute needs to be provided for each item in the list.
The type of the key attribute can only be string or number.

	<p v-for="book in books" v-bind:key="book.id">

Use v-for with v-if

When v-for is used together with v-if, v-for has a higher priority than v-if, which means that v-if will run repeatedly in each v-for loop. That is, if you need to judge whether to render certain items of the list according to conditions, you can use v-if and v-for together.

	<li v-for="plan in plans" v-if="plan.isComplete">{
    
    {
    
    plan.content}}</li> //会对循环的每一个plan分别判断if

If you only decide whether to skip the execution of the entire loop based on the true or false of a certain condition, you can place v-if on the outer element (or <template>), such as:

	<ul v-if="plans.length">
		<li v-for="plan in plans">{
    
    {
    
    plan.content}}</li>
	</ul>
	<p v-else>没有工作计划</p>

4. v-bind (one-way binding data)

Used to dynamically bind one or more attributes or props of a component to an expression in response to updating the attributes of an HTML element.

	<--绑定一个属性-->
	<img v-bind:src="imgSrc">
    <--缩写-->
    <img  :src="imgSrc">
    <--动态属性名-->
    <a v-bind:[attrname]="url"></a>
    <--内联字符串拼接-->
    <img  :src="'images/'+file/Name">
    
    data:{
    
    
    	attrname:'href',
    	url:'http://www.sina.com.cn/', 
    	imgSrc:'images/bg.jpg', 
    	fileName:'bg.jpg'
    }

The v-bind command can also directly bind an object with attributes, such as:

	<form v-bind="formObj"></form>
	data:{
    
    
		formObj:{
    
    
			method:'get, action:'#'
		}
	}

5. v-model (two-way binding data)

The v-model directive is used to create two-way data binding on forms and elements, which automatically selects the correct method to update elements based on the control <input>type <textarea>.<select>

It is essentially syntactic sugar, which refers to a certain syntax added to a computer language, which has no effect on language functions, but is more convenient for programmers to use. Usually increases the readability of the program, thereby reducing the possibility of errors in the code.

Responsible for listening to user input events to update data, and special handling for some extreme scenarios.

	<input type="text" v-model="message">
	
    data:{
    
    
    	message:'hello world'
    }

The input box will display the default message content. After the user enters, the value of the message will be updated to the content entered by the user. If you directly change the value of message, such as: vm.message="welcome", the value in the input box will also change - two-way binding.

6. v-on (monitor trigger event)

The v-on directive is used to listen to DOM events and run some JavaScript code when triggered.
The expression of the v-on directive can be a piece of JavaScript code, or it can be a method name or a method call statement.

  • ①The click event directly uses the JavaScript statement:
	<button v-on:click="count+=1">Add 1</button>
  • ②The click event is directly bound to a method:
	<button v-on:click="greet">Greet</button>
	<--缩写语法-->
	<button @click ="greet">Greet</button>
  • ③The click event uses the inline statement to call the method:
<button v-on:click="say('hi')">hi</button>

Define methods in the methods attribute object of the options object:

methods:{
    
    
	greet:function(){
    
    
		alert(this.message)
	},
	say(msg){
    
    
		alert(msg)
	}
}   //方法内this指向vm

Methods are defined in the methods property of the options object, which is an object property in which methods can be accessed through the Vue instance.

	vm.greet();
	vm.say("zhangsan");

Note: 1. Do not use arrow functions to define the methods method (such as: plus:()=>this.a++). Because the arrow function is bound to the context of the parent scope, this will not point to the Vue instance as expected, and this.a is undefined.

2. In actual development, direct writing of JavaScript statements (①) is not often used, and the form of ②③ is often used.

3. The JavaScript event attributes after calling the event will not be rendered in the page rendering result.

4. When the Vue instance is destroyed, all event handlers will be automatically deleted.

If you need to access the raw DOM event in an event-bound method, you can $eventpass it into the method using a special variable.

When deciding whether to jump according to the condition, if the condition is insufficient, you can call the preventDefault() method of the event object to prevent the jump.

When using the v-on instruction to bind an event handler, you can pass $eventin the original DOM event object, and then access the original event object in the event handler method.

	<a href="/login" v-on:click="login($event)">登录</a>
	methods:{
    
    
		login(event){
    
      
			...  
			event.preventDefault();
		}
	}

Using the event modifier .prevent has the same effect

	<a href="/login" v-on:click.prevent="login">登录</a>
	methods:{
    
    
		login(event){
    
      
			...  
		}
	}

If you want to access the original DOM original node object bound to the event, you can call event.currentTaarget to get it.

1. Event modifiers

Calling event.preventDefault() or event.stopPropagation() in an event handler is a very common requirement. Vue.js provides event modifiers, focusing on data logic without considering how to handle DOM event details.

Modifiers are indicated by a directive suffix beginning with a dot (.), immediately after the event name.

Modifiers provided for the v-on directive:

	.stop:调用event.stopPropagation()
    .prevent:调用event.preventDefault()
    .capture:添加事件监视器时使用capture模式
    .self:只当事件是从侦听器绑定的元素本身触发时才触发回调。
    .{
    
    keyCode|keyAlias}:只当事件是从特定按键触发时才触发回调。
    .native:监听组件根元素的原生事件。
    .once:只触发一次回调
    .left:只当按鼠标左键时触发
    .right:只按右键触发
    .middle:只按鼠标中键触发
    .passive:以{
    
    passive:true}模式添加侦听器

usage:

	<--阻止单击事件继续传播:-->
	<a v-on:click.stop="dothis"></a>
	<--提交事件不再重新加载页面:-->
	<form v-on:submit.prevent="dothis"></form>
	<--修饰符可以串联:-->
	<a v-on:click.stop.prevent="dothis"></a>
	<--只有修饰符:--><form v-on:submit.prevent></form>
	<--添加事件监听器时使用事件捕获模式:即内部元素触发的事件先在该事件处理函数中处理,然后交由内部元素进行处理。-->
	<div v-	on:click.capture="dothis">...</div>
	<--只当在event.target是当前元素自身时触发处理函数:即事件不是从内部元素触发的:-->
	<div v-on:click.self="dothat">...</div>
	<--单击事件处理函数只处理一次:-->
	<a c-on:click.onc="do"></a>

Description:
1. The DOM event specification supports two event models, namely capturing events and bubbling events. Capturing events start from the outermost object (most standard-compliant browsers use the window object as the outermost object) , until the object that triggers the event; the bubbling event starts from the object that triggers the event and propagates upward until the outermost object ends. Any event that occurs in the DOM event model first enters the capture phase until it reaches the target phase, and then enters the bubbling phase. The .stop and .capture modifiers provided by the v-on directive are related to this.
2. Modifiers can be used in series, but the order is important. For example, v-on:click.prevent.self will prevent all clicks, while v-on:click.self.prevent will only prevent the element itself attack.
3. If an event only needs to be responded once, you can use the .once modifier.

2. Key modifiers

When listening to keyboard events, it is often necessary to check detailed keys. To this end, you can add key modifiers when v-on listens to keyboard events.

	<--只有在按键是回车键时调用submit()方法:-->
	<input v-on:keyup.enter="submit">
	<--使用回车键的按键码:-->
	<input v-on:keyup.13="submit">

Common key code aliases

  • .enter

  • .tab

  • .delete

  • .esc

  • .space

  • .up

  • .down

  • .left

  • .right

System modifier keys: implement a listener that triggers mouse or keyboard events only when the corresponding key is pressed

  • .ctrl

  • .alt

  • .shift

  • .meta (the Windows system keyboard corresponds to the Windows logo key, the Mac system keyboard corresponds to the command key, and the Sun operating system keyboard corresponds to the solid gemstone key)

For example:

	<--Alt+C:-->
	<input @keyup.alt.67="clear">
    <--Ctrl+C:-->
    <input @keyup.ctrl.67="clear">

Note: Modifier keys are not the same as regular keys. When used with the keyup event, the modifier key must be in the pressed state when the event is triggered. In the above code, when Ctrl+c is pressed at the same time, the do() method will not be called, and the method call can only be triggered when the Ctrl key is pressed and the letter C is released. To trigger keyup.ctrl when pressing Ctrl+a key at the same time, you need to use Ctrl's virtual key code 17 instead of the Ctrl modifier key. as follows:

	<input @keyup.17.67="clear">
	<--Ctrl+click:-->
	<div @click.ctrl="do"></div>

3. The .exact modifier

The .exact modifier is new in version 2.5.0. It is used to precisely control the events triggered by the combination of system modifiers.

	<--即使同时按下Alt键或shift键,也会触发:-->
	<button @click.ctrl="onClick">A</button>
    <--只有在按住Ctrl键而不按其他键时才会触发:-->
    <button @click.ctrl.exact="onClick">A</button>
    <--只有在没有按下系统修饰键时才会触发:-->
    <button @click.exact="onClick">A</button>

4. Mouse button modifier (new in version 2.2.0)

  • .left left mouse button

  • .right right mouse button

  • .middle Middle mouse button

	<input @click.right="do"> //只有在鼠标右键单击时才会触发事件处理函数

7. v-text (update the text content of the element)

The v-text directive is used to update the text content of an element

	<span v-text="message"></span>

Equivalent to:

	<span v-text>{
    
    {
    
    message}}</span><span>{
    
    {
    
    message}}</span>

If you only update part of the text content, use { {Mustache}} interpolation.

Difference between v-text and interpolation expression { { }}

v-text will overwrite the original content in the element, and the interpolation expression { { }} will only replace its own placeholder, not the entire element content.

8. v-html (update the innerHTML of the element)

The v-html directive is used to update the innerHTML of the element, that is, the inserted text that conforms to the HTML code format will be compiled.

	<div v-html="html"></div>
	<script>
		var vm=new Vue({
    
    
			el:'#app',
			data:{
    
    
				html:"<h1>123456</h1>"
			}
		})
	</script>

equivalent to

	<div><h1>123456</h1></div>  

Note: Dynamic rendering of arbitrary HTML on a website is very dangerous as it can easily lead to XSS attacks. Remember, only use v-html on trusted content, never use v-html on user-submitted content.

9. v-once (let an element or component render only once)

The v-once directive allows an element or component to be rendered only once, this directive does not require an expression. When rendering later, the element, component, and all its children will be considered static content and skipped. Can be used to optimize update performance.

	<a v-for="n in navs" href="nav.url" v-once>{
    
    {
    
    n.name}}</a>

After using the v-once command, modifying the content of the array navs will not cause the view to be updated, because it will only be rendered once, and the rendering result will exist as static content later

10、in-for

The v-pre directive also does not require an expression and is used to skip the compilation process of this element and its child elements.
The v-pre directive can be used to display raw Mustache tags.
Using the v-pre directive for a large number of nodes without directives can speed up compilation.

<h1 v-pre> {
    
    {
    
    message}}</h1>

The output is { {message}}

11、v-cloak

No expression is required. The directive remains on the element until the associated instance is compiled, after which the directive is removed.
When used with CSS rules such as [v-cloak]{display:none}, you can hide uncompiled Mustache tags until the instance is ready.

	<html>
 		<head>
 			<style>[v-cloak]{
    
    display:none;}</style>
 		</head>
 		<body>
 			<h1 v-cloak>{
    
    {
    
    message}}</h1>
 		</body>
 	</html>

When the browser loads the page, if the network speed is slow or the page is large, it will directly display { {message}} first, and it will not be replaced with the data object until the Vue JS file is loaded, the Vue instance is created, and the template is compiled. content, the page will flicker, which is not good for user experience. Add the CSS rule [v-cloak]{display:none} and use it with the v-cloak command to solve this problem.
In the page development of the independent version of vue.js, it is very effective to use v-cloak to solve the page flickering caused by slow initialization.
But in larger projects, modular development is adopted, and the project home page has only one empty div element, and the rest of the content is completed by routing to mount different components, so there is no need to use the v-cloak command.

12、v-slot

The v-slot directive is used to provide named slots or slots that need to accept props.

2. Custom commands

In some cases, if you want to perform low-level operations on ordinary DOM elements, you need to use custom instructions. Should only be used to encapsulate manipulation of the DOM. Simplify code writing and improve reusability.

1. Registration of custom instructions

Custom instructions need to be registered before they can be used. Vue provides two registration methods

1. Global registration

Use the Vue.directive() method to register a global custom directive.
This method accepts two parameters, the first parameter is the ID (name) of the instruction, the second parameter is a definition object or function object, and the function to be implemented by the instruction is defined in this object.
Grammatical form: Vue.directive(id, [definition])
For example: Vue.directive('focus',{...})
global directives can be used in templates of any Vue instance.

	<div id="app"><input v-focus></div>
    <div id="app2"><input v-focus></div>
    <script>
    	Vue.directive('focus',{
    
    ...})    
    	new Vue({
    
    el:'#app'})   
    	new Vue({
    
    el:'#app2'})
    </script>

2. Partial Registration

Register with the directives option in the options object of the Vue instance

	new Vue({
    
    
		el:'#app',    
		directives:{
    
    
			//注册局部自定义指令    
			focus:{
    
    ...}
		}
	})

Locally registered custom directives can only be used in the view bound to this instance.

2. Hook function

The function of the custom instruction is implemented in the definition object, and the definition object is composed of hook functions.
The hook function provided by Vue:

  • bind: Called only once, when the directive is bound to the element for the first time. If the instruction needs some one-time initialization settings, it can be placed in this hook function.
  • inserted: Called when the bound element is inserted into the parent node (it can be called if the parent node exists, and does not have to exist in the document object)
  • update: Called when the VNode of the component is updated (regardless of whether the value of the instruction has changed), but it may occur before its child VNode is updated. Unnecessary template updates can be ignored by comparing the values ​​before and after the update.
  • componentUpdate: Called after the VNode of the component where the command is located and its child VNodes are all updated.
  • unbind: Called only once, when the instruction is unbound from the element.

According to the different functions to be realized by the instruction, select the corresponding hook function to write the code.

If you implement the v-focus command and automatically get the focus when the element is inserted into the parent node, you can write the auto-focus code in the inserted hook function:

	Vue.directive('focus',{
    
    
		//当绑定元素插入父节点时    
		inserted: function(el){
    
    
			//聚焦元素    
			el.focus()
		}
	})

The hook function of the instruction can take some parameters, such as:

  • el: The element bound to the instruction can directly manipulate the DOM.
  • binding: an object containing properties:
  • name: The command name, excluding the v- prefix.
  • value: The binding value of the directive. For example, in v-my-directive="1+1", the value is 2.
  • oldValue: The previous value bound by the directive, only available in update and componentUpdated hooks. Available whether or not the value has changed.
  • expression: Instruction expression in string form. For example, in v-my-directive="1+1", the expression value is "1+1".
  • arg: Arguments passed to the command, optional. For example, in v-my-directive:foo, the arg value is "foo".
  • modifiers: An object containing modifiers. For example, in v-my-directive.foo.bar, the value of the modifiers object is {foo:true,bar:true}.
  • vnode: The virtual node generated by Vue compilation.
  • oldVnode: The previous virtual node, only available in update and componentUpdated hooks.

Note: Except for the el parameter, other parameters should be read-only and must not be modified.

3. Dynamic instruction parameters

Custom directives can also use dynamic parameters. For v-my-directive:[argument]="value"example, the argument parameter can be updated according to the component instance data.

4. Function abbreviation

If the behavior of the custom instruction in the bind and update hook functions is the same, and only these two hook functions need to be used, only one function object can be passed as a parameter.

	Vue.directive('focus', 
		function(el){
    
    
			el.focus()
		}
	)

5. Object literals

If the directive requires multiple values, a JavaScript object literal can be passed in. Directives can accept all legal JavaScript expressions.

	<div v-demo="{color:'white', text:'hello!'}"></div>

Guess you like

Origin blog.csdn.net/qq_45484237/article/details/121081241