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 use custom instructions in vue

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "how to use custom instructions in vue". In daily operation, I believe many people have doubts about how to use custom instructions in vue. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use custom instructions in vue". Next, please follow the editor to study!

1. What is a custom instruction?

To use custom instructions, we first have to figure out what custom instructions are.

Custom instructions are very easy to understand, and the v-for, v-if, v-model, and so on we use are called instructions, also known as Vue built-in instructions. These instructions are all available to us directly.

In order to better meet the needs and maximize the personalized development of developers, Vue leaked the API of custom instructions to us, so that in addition to using built-in instructions, we can also define our own instructions, which are very similar to built-in instructions.

For example, the code we look at:

I am a passage.

In the above code, a lot of v-pin friends may not know what it is, it looks like an instruction, but have you ever encountered it? In fact, v-pin is a custom directive, but we omit the code to register it here.

two。 Environmental preparation

We use Vue2.x 's scaffolding tool to quickly build a project for the room.

Build command:

Vue create Project name

Get up and running:

3. How do I register a custom directive?

To use a custom instruction, we must register it in advance, just like our component, before we can use it.

Registration instructions are also divided into global registration and local registration, which is the same as global registration components and local registration components. Global registration instructions can be used directly in any component, while locally registered instructions can only be used in the place where they are registered.

3.1 Global Registration

Global registration as the name implies, after the custom directive is registered, it can be used directly in all components of the project.

Vue provides a directive method for us to register custom directives, and we register a global custom directive in main.js.

The code is as follows:

/ / src/main.jsimport Vue from "vue"; import App from ". / App.vue"; Vue.config.productionTip = false;Vue.directive ("resize", {bind () {}, inserted () {}, update () {}, componentUpdated () {}, unbind () {},}); new Vue ({render: (h) = > h (App),}). $mount ("# app")

In the previous code, we directly called the directive method provided by Vue to register the global custom instruction, which receives two parameters: the instruction name and the object containing the instruction hook function.

Once the directive is registered, we can use the directive in the form of "v-directive name" on any element in the project.

It is important to note that the instruction hook function is not necessary. You can compare it to the vue lifecycle hook function, which is used to make instructions do different things in different processes.

3.2 partial registration

Generally speaking, if the custom instruction is not used by every component, it would be fine for us to register the custom instruction.

Let's modify the APP.vue file and register the custom directive inside it as follows:

Export default {name: "App", components: {}, directives: {resize: {bind () {}, inserted () {}, update () {}, componentUpdated () {}, unbind () {},}

As shown above, Vue provides an directives option for us to register a custom directive at the same level as data and methods. In the previous code, we registered a custom directive called resize, which can only be used within the component.

Note: global registration instructions use directive, local registration instructions use directives, it is easy to understand, local instructions pay attention to register many at a time, global instructions can only register one in turn.

4. Detailed explanation of custom instruction parameters

The previous section briefly introduced the local registration custom instruction and the global registration custom instruction, you can see that there are several hook functions in the instruction, and our operation logic is mainly in these hook functions, so it is necessary for us to introduce these hook functions.

4.1 introduction to Hook function

Bind:

Called only once, the first time the instruction is bound to an element. One-time initialization settings can be made here.

Inserted:

Called when the bound element is inserted into the parent node (only the parent node is guaranteed to exist, but not necessarily inserted into the document).

Update:

Called when the VNode of the component in which it is located is updated, but may occur before its child VNode update. The value of the instruction may or may not have changed. But you can ignore unnecessary template updates by comparing the values before and after the update

ComponentUpdated:

Called after the VNode and its child VNode of the component in which the instruction is located are all updated.

Unbind:

It is called only once, when the instruction is unbound from the element.

The above five are all the hook functions of the custom instruction, each of which is optional, depending on the situation. You can simply understand the order of hook functions: when instructions are bound to elements (bind), when elements are inserted (inserted), when components are updated (update), after components are updated (componentUpdated), when instructions are unbound from elements (unbind). These are somewhat similar to the lifecycle functions of components.

4.2 introduction to the parameters of hook function

To facilitate our logical operation, each hook function receives parameters that we can use to do what we want.

El:

The element bound by the instruction can be used to directly manipulate the DOM.

Binding:

An object that contains the following properties:

Name: instruction name, excluding the v-prefix.

Value: the binding value of the instruction, for example: in "1 + 1", the binding value is 2.

OldValue: the previous value bound by the instruction, available only in update and componentUpdated hooks. Available regardless of whether the value changes or not.

Expression: instruction expression in the form of a string. For example, in "1 + 1", the expression is "1 + 1".

Arg: the parameter passed to the instruction, optional. For example, in v-my-directive:foo, the parameter is "foo".

Modifiers: an object that contains modifiers. For example: in v-my-directive.foo.bar, the modifier object is {foo: true, bar: true}.

Vnode:

The virtual node generated by Vue compilation.

OldVnode:

The last virtual node, available only in update and componentUpdated hooks.

The el and binding parameters are the most mundane we use when using them, and with these parameters, our operation becomes easier.

5. Simple cases listed in actual combat

The above two sections describe how to register custom instructions and related parameters, and then it's time to practice. Let's define a custom instruction in APPVue to verify the execution of the hook function.

The code is as follows:

Vue logo

Export default {name: "App", components: {}, directives: {resize: {bind () {console.log ("bind")}, inserted () {console.log ("inserted")}, update () {console.log ("update")}, componentUpdated () {console.log ("componentUpdated")} Unbind () {console.log ("unbind")},}

The effect is as follows:

In the above code, we bind the custom instruction resize to the div element. When we refresh the page, we execute the bind and inserted hook functions in the custom instruction, and the rest of the functions will not be executed until the element is updated.

5.1 implement v-resize instruction

Demand background:

When doing large data screen or adaptive development, we usually need to re-render the page according to the size of the browser window, such as redrawing echarts charts and other functions.

Requirements description:

Realize the custom instruction v-resize instruction, when the window size changes, print the latest window width and height in real time.

Code implementation:

/ / src/APP.vue window width: {{innerWidth}} window height: {{innerHeight}} export default {name: "App", data () {return {innerHeight: window.innerHeight, innerWidth: window.innerWidth,};}, components: {}, directives: {resize: {bind () {console.log ("bind") }, inserted (el, binding, vnode) {console.log ("inserted"); console.log (el, binding); let that = vnode.context; / / listening on the browser's resize event window.addEventListener ("resize", () = > {that.innerHeight = window.innerHeight; that.innerWidth = window.innerWidth;}) }, update () {console.log ("VNode updated");}, componentUpdated () {console.log ("componentUpdated");}, unbind () {console.log ("unbind"); window.removeEventListener ("resize");},}

The effect is as follows:

When we change the size of the browser window, the latest height and width will be printed on the page in real time, of course, this is only the simplest case, in the actual project, we usually call some custom methods after the window size changes.

5.2 instruction to pass parameters and values

When we use v-bind, v-model and other built-in instructions, we can pass parameters and values, and so can our custom instructions.

Sample code:

Window width: {{innerWidth}} window height: {{innerHeight}} export default {name: "App", data () {return {innerHeight: window.innerHeight, innerWidth: window.innerWidth, args: "I am the parameter", value: "I am the passed value",} }, components: {}, directives: {resize: {bind (el, binding) {console.log ("bind"); console.log ("value", binding.value); console.log ("Parameter", binding.arg);},}

The effect is as follows:

Args and value are the parameters and values that we pass to the instruction. It is important to note that value receives variables or expressions, and arg receives strings or variables. For more information, please see the parameter explanation section.

5.3 instruction abbreviation

Many times we don't need to use all the hook functions in custom instructions, there are only a few commonly used, so officials have provided us with a way to abbreviate them.

The code is as follows:

Resize (el, binding) {console.log ("I am an abbreviated custom instruction", binding.value);}

The way the above code is written makes our instructions very concise. The previous code means to combine bind and update hook functions into one, which we usually use when we want these two hook functions to do the same thing.

6. Custom instruction usage scenario

Knowing how to use custom instructions, we can expand the usage scenario and deepen your understanding of custom instructions.

6.1 v-copy

Achieve one-click copy of the text content, for right-mouse button paste.

6.2 v-longpress

To achieve a long press, the user needs to press and hold the button for a few seconds to trigger the corresponding event.

6.3 v-debounce

To prevent the button from being clicked multiple times in a short period of time, use the anti-shake function to limit the time to be clicked only once.

6.4 v-LazyLoad

Implement a picture lazy load instruction to load only the pictures in the visible area of the browser.

6.5 v-draggable

Implement a drag-and-drop instruction that can drag and drop elements arbitrarily in the visual area of the page.

At this point, the study on "how to use custom instructions in vue" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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: 0

*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