Detailed explanation of filters and directives in Vue

Detailed explanation of filters and directives in Vue

There are two types of filters in Vue: local filters and global filters

Filters can be used for some common text formatting. Filters can be used in two places: double curly brace interpolation and v-bind expressions (the latter is supported since 2.1.0+). Filters should be added at the end of a JavaScript expression, indicated by the "pipe" symbol (official documentation)

<!-- in double curly braces -->
{{ message | capitalize }}

<!-- In `v-bind` -->
<div v-bind:id="rawId | formatId"></div>

1. Define a global filter without parameters

Vue.filter('capitalize', function(msg) {// msg is a fixed parameter, which is the data you need to filter if (!value) return ''
            value = value.toString()
            return value.charAt(0).toUpperCase() + value.slice(1)
       })

2. Define a global filter with parameters

 <div id="app">
            <p>{{ msg | msgFormat('crazy','--')}}</p>
        </div>

        <script>
            // Define a Vue global filter named msgFormat
            Vue.filter('msgFormat', function(msg, arg, arg2) {
                // string replace method, the first parameter, in addition to writing a string, can also define a regular return msg.replace(/simple/g, arg+arg2)
            })
      </script>

3. Local filter

The definition and usage of local filters with and without parameters are the same as those of global filters. The only difference is that local filters are defined in the vue instance. The area where it works is also the area controlled by the vue instance

 // Create a Vue instance and get the ViewModel
            var vm = new Vue({
                el: '#app',
                data: {
                    msg: 'msg'
                },
                methods: {},
                //Define private local filters. Filters can only be used in the current vue object: {
                    dataFormat(msg) {
                        return msg+'xxxxx';
                    }
                }
            });

vue custom directive

Vue has many built-in instructions, such as v-model, v-show, v-html, etc., but sometimes these instructions cannot satisfy us, or we want to add some special functions to the elements. At this time, we need to use a very powerful function in Vue - custom instructions.

Before we begin, we need to make it clear that the problem or usage scenario that custom instructions solve is to perform low-level operations on ordinary DOM elements, so we cannot use custom instructions blindly.

Global Directives

Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus element el.setAttribute('placeholder', 'This is added by a custom instruction')
    el.focus()
  }
})

Local instructions

directives: {
  focus:
    // Definition of instruction inserted: function (el) {
      el.focus()
    }
  }
}

use

<input v-focus>

Hook functions (both optional)

bind: Called only once, when the directive is first bound to an element. Here you can perform a one-time initialization setup.

inserted: called when the bound element is inserted into the parent node (it only guarantees that the parent node exists, but has not necessarily been inserted into the document).

update: Called when the VNode of the component is updated, but it may happen before its child VNodes are updated. 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 (see below for detailed hook function parameters).

componentUpdated: Called after the VNode of the component where the instruction is located and its child VNodes are all updated.

unbind: Called only once, when the directive is unbound from the element.

Usage and parameters

Execute in order

//Custom directive Vue.directive('focus', {
  bind: function (el, binding, vnode) {
    console.log("1")
  },
  inserted: function (el, binding, vnode) {
    console.log("2");
  },
  update: function (el, binding, vnode, oldVnode) {
    console.log("3");
  },
  componentUpdated: function (el, binding, vnode, oldVnode) {
    console.log('4');
  },
  unbind: function (el, binding, vnode) {
    console.log('5');
  }
})

The above is a detailed explanation of the filter and directive in Vue. For more information about the filter and directive in Vue, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of Vue filter implementation and application scenarios
  • How to use vue filter
  • Steps to encapsulate global filters in Vue
  • How to use the filter vue.filters
  • Detailed explanation of application scenarios of filters in Vue

<<:  Raspberry Pi msmtp and mutt installation and configuration tutorial

>>:  Summary of Docker configuration container location and tips

Recommend

js canvas realizes slider verification

This article example shares the specific code of ...

Window.name solves the problem of cross-domain data transmission

<br />Original text: http://research.microso...

How to solve the problem that Seata cannot use MySQL 8 version

Possible reasons: The main reason why Seata does ...

User needs lead to marketing-oriented design

<br />For each of our topics, the team will ...

How to optimize a website to increase access speed update

Recently, the company has begun to evaluate all s...

Summary of 28 common JavaScript string methods and usage tips

Table of contents Preface 1. Get the length of a ...

Axios secondary encapsulation example Demo in the project

1. Why do packaging? Facilitates overall code cal...

Detailed explanation of putting common nginx commands into shell scripts

1. Create a folder to store nginx shell scripts /...

Detailed example of clearing tablespace fragmentation in MySQL

Detailed example of clearing tablespace fragmenta...

6 interesting tips for setting CSS background images

Background-image is probably one of those CSS pro...