Vue.js Learning Four (directives and custom directives)

Source: Internet
Author: User
Tags event listener modifiers

The official instructions have been very simple, and here again, but also to deepen their impressions

V-text is written purely text, you can ignore this command direct double curly braces instead of

<v-text= "msg"></span><!--  -<span>{msg}}</span >

v-html Update the InnerHTML of the element, you can use this command if the retrieved value contains the HTML style.

The following is a copy of the official note, for the user input HTML, the display should be handled with care. If it is the server's own generated HTML, completely developer-controlled code, you can ignore

Note: content is inserted as normal HTML-not compiled as Vue template. If you try to use v-html a composite template, you can reconsider whether to replace it by using a component.

Dynamically rendering arbitrary HTML on a Web site is dangerous because it can easily lead to XSS attacks. Use only on trusted content v-html and never on content submitted by users.

V-show

Toggles the CSS properties of an element based on the true or false value of the expression display .

The directive triggers a transition effect when the condition changes.

In short, control whether the label of the current instruction is displayed

V-if,v-else, V-else if

Renders an element based on the true or false condition of the value of an expression. The element and its data bindings/components are destroyed and rebuilt at the time of the switchover. If the element is <template> , it will be presented with its contents as a conditional block.

The directive triggers a transition effect when the condition changes.

Conditional judgment, here simple conditions to judge the line, complex judgment or directly in the model to deal with it.

V-on

Binds the event listener. The event type is specified by the parameter. The expression can be either the name of a method or an inline statement, which can be omitted if no modifiers are present.

When used on ordinary elements, only native DOM events can be monitored. When used on a custom element component, you can also listen for custom events that are triggered by the child component.

When listening to native DOM events, the method takes an event as a unique parameter. If you use an inline statement, the statement can access a $event property: v-on:click="handle(‘ok‘, $event)" .

Modifier

    • .stop-Called event.stopPropagation() .
    • .prevent-Called event.preventDefault() .
    • .capture-Use capture mode when adding event listeners.
    • .self-Triggers a callback only if the event is triggered from the element itself that the listener binds to.
    • .{keyCode | keyAlias}-Triggers a callback only if the event is triggered from a specific key.
    • .native-Listens for native events of component root elements.
    • .once-Only one callback is triggered.
    • .left-(2.2.0) is triggered when the left mouse button is clicked.
    • .right-(2.2.0) is triggered when the right mouse button is clicked.
    • .middle-(2.2.0) triggers when the middle mouse button is clicked.
    • .passive-(2.3.0) { passive: true } adding listeners in a pattern
<!--Method Processing Device -<ButtonV-on:click= "Dothis"></Button><!--Inline Statements -<ButtonV-on:click= "Dothat (' Hello ', $event)"></Button><!--Abbreviations -<Button@click= "Dothis"></Button><!--Stop bubbling -<Button@click. Stop= "Dothis"></Button><!--block default behavior -<Button@click. Prevent= "Dothis"></Button><!--block default behavior, no expression -<form@submit. Prevent></form><!--concatenation modifier -<Button@click. Stop.prevent= "Dothis"></Button><!--key modifiers, key aliases -<input@keyup. Enter= "OnEnter"><!--key modifier, key code -<input@keyup.= "OnEnter"><!--clicking the callback will only trigger once -<Buttonv-on:click.once= "Dothis"></Button>

Listen for custom events on subcomponents (the event handler will be called when the subassembly Fires "My-event"):

<my-component@my-event= "Handlethis"></my-component><!--Inline Statements -<my-component@my-event= "Handlethis (123, $event)"></my-component><!--native events in the component -<my-component@click. Native= "OnClick"></my-component>

Note that the above limitations on the Vue version are not supported by the lower version! It is mainly applicable to the handling of all kinds of events.

V-bind

Dynamically binds one or more attributes, or one component property to an expression.

When binding a property, the property must be declared in the subassembly. You can specify different binding types with modifiers.

When there are no parameters, you can bind to an object that contains a key-value pair. Note at this time class and the style binding does not support arrays and objects.

V-model

The V-model directive creates two-way data binding on the form control element. It automatically picks the correct method to update the element based on the type of control.

Commonly used form controls such as SELECT, Input,textarea, etc.

If the value of the select binding is directly selected, the other input directly selects the text

V-pre

The official explanation is: Skip the compilation of this element and its child elements. Can be used to display the original mustache label. Skipping a large number of nodes without instructions speeds up compilation.

I haven't used it so far.

V-cloak

This instruction remains on the element until the associated instance finishes compiling. When used with CSS rules such as [V-cloak] {Display:none}, this directive hides the mustache tags that are not compiled until the instance is ready to complete.

This command uses a special scenario and displays the original code at initialization time, such as

<v-for= "Item in Items">  <li> {{Item.name}} </ Li > </ ul >

Display when page load is not completed

{{Item.name}}

This time if you add this directive label on UL

<v-cloak v-for= "Item in Items">  <Li  >{{item.name}}</li></ul>

Then add the corresponding global CSS

[V-cloak] {  display:none;}

When the page initialization is incomplete, the entire label will be hidden and the label will be removed automatically after loading, showing the complete result.

V-once

Renders elements and components only once . Subsequent re-rendering, the element/component and all of its child nodes will be treated as static content and skipped. This can be used to optimize update performance.

  <v-once>      <p>{{msg}}</ P >    </ Div >    <  v-on:click= "ChangeValue"> Click to change the value of msg </Div  >

We bind a click event to try to modify the value of the MSG after the page rendering is complete, and the event triggers the contents of this tag to no longer change.

---------------------------------------------------------------------------------------------------------

The label content has a direct copy of the description on the official webpage, partly with a simple example

All the content to try again, or some unexpected receipt

May just start the project using the process, only to use a part of the instructions, after all to understand once again, I have the original project part of the function has been modified again

Some of the functions of an instruction can be completed, I may use a number of instructions to collaborate to complete, after all, just beginning to look at the official documents, not very comprehensive

Read the document or try it more, deepen the impression and use it more handy in the future.

A custom directive is attached below

Main.js

import vue from ' Vue ' import app./app ' import router from './router ' Vue.config.productionTip = Falsevue.directiv E (' title ', {  inserted:function (el, binding) {let    title = Binding.value;    if (title) {      document.title = Binding.value;    }}}  ); * eslint-disable no-new */new Vue ({  el: ' #app ',  router,  Template: '<app /> ', components  : {App}})

And then we can use the V-title command in our Vue file.

<Template>    <DivV-title= "' Here is the title '">here is the content</Div></Template><Script>Exportdefault{name:'Home', components: {}, data () {return {        }    }}</Script><styleLang= "Scss"scoped></style>

Note the contents of the instruction inside the single quotation mark identifies this is a string, without single quotation marks, the instruction value represents the name of the variable, to declare the corresponding variable name in the data

<Template>    <DivV-title= "title">here is the content</Div></Template><Script>Exportdefault{name:'Home', components: {}, data () {return{title:"here is the title"        }    }}</Script><styleLang= "Scss"scoped></style>

Global directive registration belongs to global API, global registration instruction usage

Register vue.directive (' my-directive ', {  bind:function () {},  inserted:function () {},  update:function () {},< C4/>componentupdated:function () {},  unbind:function () {}})//register (pass in a simple instruction function) vue.directive (' My-directive ', function () {  //This will be called by ' bind ' and ' Update '})

The instruction definition function provides several hook function descriptions, only the functions that need to be declared, and what is not needed can be omitted:

    • bind: Called only once, when the instruction is first bound to an element, this hook function allows you to define an initialization action that executes once at the time of the binding.

    • inserted: Called when the binding element is inserted into the parent node (the parent node exists to be called and does not have to exist in document).

    • update: Called when the template that contains the binding element is updated, regardless of whether the binding value changes. You can ignore unnecessary template updates by comparing the binding values before and after the update.

    • componentUpdated: Called when the template on which the binding element is completing an update cycle.

    • unbind: Called only once when the instruction is unbound from the element.

The hook function is given the following parameters:

    • El: The element that the directive binds to, which can be used to manipulate the DOM directly.
    • Binding: An object that contains the following properties:
      • Name: directive name, not including v- prefix.
      • Value: The binding value of the directive, for example: v-my-directive="1 + 1" , the value is 2 .
      • OldValue: The previous value of the directive binding, only update available in and componentUpdated hooks. It is available regardless of whether the value is changed.
      • Expression: The string form of the bound value. For example v-my-directive="1 + 1" , the value of expression is "1 + 1" .
      • ARG: The argument passed to the instruction. For example v-my-directive:foo , the value of ARG is "foo" .
      • Modifiers: An object that contains modifiers. For example: v-my-directive.foo.bar , the Modifier object modifiers the value is { foo: true, bar: true } .
    • Vnode:vue compile the generated virtual node, consult the Vnode API for more details.
    • Oldvnode: The previous virtual node is available only in update and componentUpdated hooks.

Parameters are used as follows

vue.directive (' demo ', {bind:function (El, binding, Vnode) {var s = json.stringify el.innerhtml = ' Name: ' + S (binding.name) + '<BR>' + ' value: ' + S (binding.value) + '<BR>' + ' expression: ' + S (binding.expression) + '<BR>' + ' argument: ' + S (binding.arg) + '<BR>' + ' modifiers: ' + S (binding.modifiers) + '<BR>' + ' vnode keys: ' + Object.keys (vnode). Join (', ')}})

Directive has the advantage of binding page element values, such as displaying values on some Web pages that need to retain two decimal places

However, when it comes to CSS styles that require accompanying elements, you need to include some parameter controls, or choose to use plug-ins to resolve them.

Vue.js Learning Four (directives and custom directives)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.