Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to manually encapsulate custom instructions in Vue

2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to manually encapsulate custom instructions in Vue". In the operation of actual cases, many people will encounter this dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In the front-end basic interview, Vue's instruction is regarded as a high-frequency interview question.

Interviewer: what are the instructions of Vue?

Just tell him: as of Vue3.2,Vue, there are 16 self-contained instructions, including:

V-text, v-html, v-show, v-if, v-else, v-else-if, v-for, v-on, v-bind, v-model, v-slot, v-pre, v-cloak, v-once, v-memo, v-is, of which v-memo is added and v-is is abandoned in 3.1.0

If the interviewer further asks: how to encapsulate a custom instruction?

Just tell him: custom instructions are divided into global custom instructions and local instructions; in Vue3, you can register a global custom instruction through directive () on the application instance. If you want to register a local instruction, you can configure the directives option in the component to register the local instruction.

After reading this article, you will have a comprehensive understanding of the 16 Vue instructions and how to customize one instruction

1. Brief introduction

1.1 what is the Vue instruction

In Vue, instructions are actually special attributes

Vue will do something behind the back according to the instructions. as for what to do, Vue will perform different operations according to different instructions, which will be said later.

1.2 what are the characteristics

An obvious feature of Vue instructions is that they all start with v -, for example: v-text

two。 Built-in instruction

2.1 what are the built-in instructions in Vue?

Built-in instructions refer to Vue's own instructions, which can be used out of the box.

Vue has a total of 16 built-in instructions, including:

V-text, v-html, v-show, v-if, v-else, v-else-if, v-for, v-on, v-bind, v-model, v-slot, v-pre, v-cloak, v-once, v-memo, v-is, of which v-memo is added and v-is is abandoned in 3.1.0

Let's take a look at the basic use of these built-in instructions

2.2 understand the basic use of 16 built-in instructions

2.2.1 v-text

The purpose of v-text is to update the textContent of an element, for example:

The content of the H2 element ultimately depends on the value of msg

2.2.2 v-html

Much like v-text, except that v-html is used to update the innerHTML of elements, such as

It should be noted that the contents must be inserted according to normal HTML.

2.2.3 v-show

V-show can switch the display value of an element according to the true or false value of the expression, which is used to control the display and hiding of the element, for example:

As you can see, when the condition changes, the instruction triggers the transition effect that is shown or hidden

Note: v-show does not support elements, nor does it support v-else

2.2.4 v-if

V-if is used to conditionally render elements based on the true and false values of the expression

Compared with v-show, v-if is the destruction or reconstruction of elements when switching, rather than simply showing and hiding.

You can see that when the expression is false, v-if destroys the element directly, while v-show just hides it visually.

And v-if can be, if the element is, extract its contents as a conditional block

2.2.5 v-else

V-else does not need an expression, which means to add a "else block", which is equivalent to showing the elements of v-if when v-if meets the conditions, otherwise showing the elements of v-else, for example:

Note: the previous sibling element of v-else must have v-if or v-else-if

2.2.6 v-else-if

By the same token, the "else if block" that represents v-if, like v-else, the previous sibling element must have v-if or v-else-if, for example:

2.2.7 v-for

V-for an instruction for iteration that renders elements or template blocks multiple times based on the source data, for example:

You can also specify aliases or keys for objects for array indexes

2.2.8 v-on

V-on is used to bind events to elements, which can be abbreviated to: @

Modifier

.stop-call event.stopPropagation ()

.rooment-call event.preventDefault ()

.capture-use capture mode when adding event listeners

.self-triggers the callback only if the event is triggered from the listener bound element itself

. {keyAlias}-A callback is triggered only if the event is triggered from a specific key

.once-only one callback is triggered

.left-triggered only when the left mouse button is clicked

.right-triggered only when the right mouse button is clicked

.middle-triggered only when the middle mouse button is clicked

.passive-{passive: true} mode to add listeners

For example:

It is important to note that when used on ordinary elements, you can only listen for native DOM events. When used on custom element components, you can also listen for custom events triggered by subcomponents

2.2.9 v-bind

V-bind is used to bind data and element attributes, which can be abbreviated to: or. (when using the .prop modifier), such as

Three modifiers of v-bind

.camel-convert kebab-case attribute name to camelCase

.prop-Force a binding to a DOM property. 3.2 +

.attr-Force a binding to a DOM attribute. 3.2 +

2.2.10 v-model

V-model is limited to:

Components

3 modifiers for v-model:

Lazy-lazy update, listening for change events instead of input events

.number-enter a string to be a valid number

.trim-enter leading and trailing space filtering

You can create two-way bindings on a form control or component, for example:

2.2.11 v-slot

V-slot is used to provide named slots or slots that need to receive prop

Optional parameter passed, indicating the slot name. Default is default.

2.2.12 v-pre

The v-pre directive is used to skip the compilation of this element and its child elements, such as:

You can see that what's in it hasn't been compiled.

2.2.13 v-cloak

V-cloak instruction is mainly used to solve the problem of interpolation expression flickering on the page.

{{message}} [v-cloak] {display: none;}

In this way, div will only be displayed at the end of compilation.

2.2.14 v-once

The v-once command is used to indicate that the element / component and all its child nodes will be treated as static content and skipped when re-rendered.

2.2.15 v-memo 3.2 +

Used to cache the subtree of a template

The instruction receives a fixed-length array as a dependent value for memory comparison. If each value in the array is the same as the last rendering, updates to the entire subtree are skipped

If both valueA and valueB remain the same during re-rendering, updates to this and all of its child nodes will be skipped

2.2.16 v-is

Abandoned in 3.1.0, use is instead

3. Custom instruction

3.1 how to customize an instruction

3.1.1 Global Custom Directive

We also mentioned in the preface that you can register a global custom directive in Vue3 through directive () on the application instance. For example, an example given by the government

Const app = Vue.createApp ({}) / / registers a global custom directive `v-focus`app.directive ('focus', {/ / when the bound element is mounted in DOM. Mounted (el) {/ / focus element el.focus ()}})

In the above code, the application instance app is obtained through Vue.createApp ({}). There is a directive () on the application instance app, which is used to create a global custom directive.

It is also very simple to use, such as

3.1.2 registering local instructions

If you want to register a local instruction, configure the directives option in the component to register the local instruction, or take v-focus as an example:

Directives: {focus: {/ / definition of instruction mounted (el) {el.focus ()}

3.1.3 questions

From the above example, we can see that whether using directive custom global directives or using directives to configure local directives, an instruction name, such as focus, is required.

What is the mounted in the specific configuration object? What is the el in mounted? What are the parameters besides mounted and el?

3.1.4 Hook functions (7)

To get to the point, mounted is actually the hook function of the instruction, indicating that the component is called after it is mounted, while el is the element to which the instruction is bound.

Here we mainly talk about hook functions. Besides mounted, there are other instruction hooks, all of which are optional.

Created: called before the attribute or event listener of the bound element is applied

BeforeMount: called when an instruction is first bound to an element and before the parent component is mounted

Mounted: called after the parent component of the bound element is mounted

BeforeUpdate: called before updating the VNode containing the component

Updated: called after the VNode update of the VNode that contains the component and its subcomponents

BeforeUnmount: called before unloading the parent component of a bound element

Unmounted: called only once when the instruction is unbound from the element and the parent component has been unloaded

3.1.5 four parameters of the hook function

The four parameters of the hook function are optional, which are

El: used to directly manipulate DOM, indicating the element to which the instruction is bound

Binding object: contains the following six properties

Instance: an example of a component that uses instructions

Value: the value passed to the instruction

OldValue: previous valu

Arg: the parameter passed to the instruction

Modifiers: the modifier passed to the instruction

Dir: an object, which is actually the configuration object passed when registering an instruction

Vnode: virtual DOM, a blueprint for real DOM elements, corresponding to el

PrevNode: last virtual node

3.2 manually encapsulate custom instructions

Knowing the basics, we can manually encapsulate a custom instruction v-pin, which means to set something on the page

3.2.1 create a Vue project

First, use vite to build the Vue3 project

Npm init vite@latest

Finally, according to the prompt, start the project using npm run dev

Of course, you can also use other parties.

We know that Vue custom instructions have two ways: global registration and local registration. For convenience, I will register v-pin in the global.

3.2.2 achieve effect

I want to talk about arbitrarily setting the specified location, such as positioning the logo in the above figure in the upper right corner, the code is as follows:

/ / main.jsimport {createApp} from 'vue'import App from'. / App.vue'const app = createApp (App) app.directive ('pin', {mounted (el, binding) {/ / whether to fix the modifier passed in var pinned = binding.value; / / indicates where var position = binding.modifiers / / the parameter passed to the instruction, which can indicate the importance var args = binding.arg; if (pinned) {el.style.position = 'fixed'; if (args = = "warning") {/ / simply set the style to distinguish el.style.backgroundColor = "pink" } for (var val in position) {if (position [val]) {el.style [val] = '10pxrabbit;} else {el.style.position =' static'; el.style.backgroundColor = "" }) app.mount ('# app')

It is also easy to use, as follows

The result is shown in the figure:

3.2.3 improve the structure

To make it easier to register more custom instructions in the future, we modify the code structure

First, create a new folder, directives, that is dedicated to placing instructions

Then write each custom instruction as an object and export it as follows: directives\ pin.js

Const pin = {mounted (el, binding) {/ / whether to fix the modifier passed in var pinned = binding.value; / / indicates where var position = binding.modifiers; / / the parameter passed to the instruction, and can indicate the importance var args = binding.arg; if (pinned) {el.style.position = 'fixed' If (args = = "warning") {el.style.backgroundColor = "pink";} for (var val in position) {if (position [val]) {el.style [val] = '10pxrabbit;} else {el.style.position =' static'; el.style.backgroundColor = ";}} export default pin

Next, create an index.js under the directives folder, import all the instructions here, put them in directives, and then export an install method

Import pin from'. / pin'const directives = {pin} export default {install (app) {Object.keys (directives). ForEach ((key) = > {app.directive (key, directives [key])})},}

Finally, in main.js, the install method is called through use (), so all instructions are registered in batches.

Import {createApp} from 'vue'import App from'. / App.vue'import Directives from'. / directives'const app = createApp (App) app.use (Directives) app.mount ('# app')

After refreshing, the result is the same.

This is the end of "how to manually encapsulate custom instructions in Vue". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 285

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report