Detailed explanation of Vue filter implementation and application scenarios

Detailed explanation of Vue filter implementation and application scenarios

1. Brief Introduction

Vue.js allows you to define your own filters, which 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:

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

<!-- In `v-bind` -->
<div v-bind:msg="message | filter"></div>

Filter functions always receive the value of an expression as first argument.

In the above example, the filter function will receive the value of message as the first argument.

1.1 Filters can be connected in series

{{ message | filterA | filterB }}

In this example, filterA is defined as a filter function that accepts a single parameter. The value of the expression message is passed into the function as a parameter. Then continue to call the filter function filterB, which is also defined to receive a single parameter, and pass the result of filterA to filterB.

1.2 Filters are JavaScript functions that can receive parameters

{{ message | filterA('arg1', arg2) }}

filterA is defined as a filter function that accepts three parameters. The value of message is the first parameter, the ordinary string 'arg1' is the second parameter, and the value of expression arg2 is the third parameter.

2. Define global filters in vue-cli

Syntax: Vue.filter( filterName, ( ) => { return // data processing results} )

eg:

<div id="app">
  <h3>{{userName | addName}}</h3>
</div>
<script>
// Parameter 1: is the name of the filter, that is, the processing function after the pipe character;
// Parameter 2: processing function, the parameters of the processing function are the same as above	
Vue.filter("addName",(value)=>{											            
    return "my name is" + value
})
let vm = new Vue({
    el:"#app",
  	data:{
     userName:"Xiaoming" 
    }
})
</script>

2.1 Actual development and use

Global filters are often used for data modification. Usually we extract the processing functions and put them in a .js file.

// filter.js filelet filterPrice = (value) => {
	return 'received' + value + 'yuan'
}
let filterDate = (value) => {
    return value + 'day'
}

export default {filterPrice,filterDate}

Import the above filter.js file in main.js. You can also import the filter.js file in any component, but for global filters, it is best to define it in main.js. What is imported is an object, so use the Object.keys() method to get an array of keys, traverse the data, let the key be the name of the global filter, followed by the processing function corresponding to the key, so that the global filter can be used in any component:

//main.js
 
// Below are 2 ways to import, the first one is recommended import * as filters from './utils/filter/filter'
// import {filterPrice,filterDate} from './utils/filter/filter'
 
console.log(filters)
 
Object.keys(filters.default).forEach((item)=>{
  Vue.filter(item,filters.default[item])
})
 
new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')

3. Use global filters in components:

//test.vue

<template>
  <div>
    <input type="text" v-model="filterCount" >
    <div>{{filterCount | filterPrice}}</div>
    <div>{{filterCount | filterDate}}</div>
  </div>  
</template>

<script>
export default {
  data(){
    return {
      filterCount:1500
    }
  },
}
</script>

3. Define local filters in vue-cli

//test.vue

<template>
  <div>
    <input type="text" v-model="filterCount" >
    <div>{{filterCount | filterPrice}}</div>
    <div>{{filterCount | filterDate}}</div>
  </div>  
</template>

<script>
export default {
  data(){
    return {
      filterCount:1500
    }
  },
}
</script>

4. Common usage scenarios

4.1 Format date (time)

Scenario 1: Time sent from the backend: 2019-11-19T04:32:46Z

Install moment.js

// main.js

import moment from 'moment'
// Define global filter - time format Vue.filter('format',function(val,arg){
  if(!val) return;
  val = val.toString()
  return moment(val).format(arg)
})

//test.vue

<template>
   <div class="filter">{{time | format('YYYY-MM-DD HH:MM:SS')}}</div>  
</template>

<script>
export default {
  data(){
    return {
      time:'2019-11-19T04:32:46Z'
    }
  }
}
</script>

Summarize

This is the end of this article about Vue filter implementation and application scenarios. For more relevant Vue filter implementation and application content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of VUE's data proxy and events
  • A brief discussion on the principle of Vue's two-way event binding v-model
  • Detailed explanation of Vue dynamic components and global event binding summary
  • Usage of Vue filters and timestamp conversion issues
  • Detailed explanation of Vue's data and event binding and filter filters

<<:  MySQL partitioning practice through Navicat

>>:  Detailed tutorial on installing VirtualBox and Ubuntu 16.04 under Windows system

Recommend

About Vue virtual dom problem

Table of contents 1. What is virtual dom? 2. Why ...

Summary of the use of CSS scope (style splitting)

1. Use of CSS scope (style division) In Vue, make...

jQuery achieves breathing carousel effect

This article shares the specific code of jQuery t...

JavaScript to achieve dynamic table effect

This article shares the specific code for JavaScr...

MySQL encryption and decryption examples

MySQL encryption and decryption examples Data enc...

HTML background color gradient achieved through CSS

Effect screenshots: Implementation code: Copy code...

Docker volumes file mapping method

background When working on the blockchain log mod...

The use of v-model in vue3 components and in-depth explanation

Table of contents Use two-way binding data in v-m...

React Native scaffolding basic usage detailed explanation

Build the project Execute the command line in the...

Solutions to common problems using Elasticsearch

1. Using it with redis will cause Netty startup c...

Summary of important components of MySQL InnoDB

Innodb includes the following components 1. innod...

How to monitor and delete timed out sessions in Tomcat

Preface I accidentally discovered that the half-h...