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

Basic concepts and common methods of Map mapping in ECMAScript6

Table of contents What is a Mapping Difference be...

N ways to cleverly implement adaptive dividers with CSS

Dividing lines are a common type of design on web...

How to connect to virtual machine MySQL using VScode in window environment

1. Virtual Machine Side 1. Find the mysql configu...

JavaScript to achieve custom scroll bar effect

In actual projects, the up and down scroll bars a...

JavaScript knowledge: Constructors are also functions

Table of contents 1. Definition and call of const...

Can asynchrony in JavaScript save await?

I knew before that to synchronously obtain the re...

mysql8.0.23 linux (centos7) installation complete and detailed tutorial

Table of contents What is a relational database? ...

Interviewers often ask questions about React's life cycle

React Lifecycle Two pictures to help you understa...

Several implementation methods of the tab bar (recommended)

Tabs: Category + Description Tag bar: Category =&...

A Deep Dive into JavaScript Promises

Table of contents 1. What is Promise? 2. Why is t...

How to deploy Tencent Cloud Server from scratch

Since this is my first post, if there are any mis...

Method and introduction of table index definition in MySQL

Overview An index is a table of correspondence be...

Common pitfalls of using React Hooks

React Hooks is a new feature introduced in React ...

Advantages and Problems of XHTML CSS Website Design

XHTML is the standard website design language cur...