Vue global registration filter filter

With the continuous update of vue's scaffolding, many things need to be configured by ourselves when building a project, such as filters.

Take my personal habit as an example:
1. Create a filters.js file and define multiple filters here

//时间过滤器
let formatTime = time => {
    
    
	if (time) {
    
    
		var a = new Date(time).toJSON();
		var date = new Date(+new Date(a) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{
    
    3}Z/, '')
		return date
	}
}
export {
    
     formatTime };

2. Introduce it in main.js and use it

//过滤器
import * as filters from './filters/index.js'
Object.keys(filters).forEach(key => {
    
    
    Vue.filter(key, filters[key])
})

3. Use filters globally

<p>{
    
    {
    
     time | formatTime }}</p>

There is a question : Why is Object.keys written like this when using it?

First: The
Vue.filter method receives two parameters (filter name, filter function)

Secondly:
import * as filters from'./filters/index.js' This import will get all the filters exposed in the filter.js file through filters. The data structure of filters is

{
    
    
	过滤器名1:过滤器函数1,
	过滤器名2:过滤器函数2,
}

Use the Object.keys method to take out all the keys to generate an array, and use forEach to traverse the array and pass the key and the corresponding value as parameters to the Vue.filter method, so that each custom filter can be bound to the vue filter. .

Guess you like

Origin blog.csdn.net/weixin_43299180/article/details/114671640