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

Issues with upgrading Python and installing Mongodb drivers under Centos

Check the Python version python -V If it is below...

Detailed process of using Vscode combined with docker for development

Preface Using Docker and VS Code can optimize the...

Element sample code to implement dynamic table

Table of contents 【Code background】 【Code Impleme...

How to create a MySQL master-slave database using Docker on MacOS

1. Pull the MySQL image Get the latest MySQL imag...

JavaScript to achieve simple image switching

This article shares the specific code for JavaScr...

Vue SPA first screen optimization solution

Table of contents Preface optimization SSR Import...

Implementation of MySQL joint index (composite index)

Joint Index The definition of the joint index in ...

Docker builds Redis5.0 and mounts data

Table of contents 1. Simple mounting of persisten...

JavaScript flow control (loop)

Table of contents 1. for loop 2. Double for loop ...

Vue3.x uses mitt.js for component communication

Table of contents Quick Start How to use Core Pri...