Use of Vue2 and Vue3 filters

Filters are also relatively common in daily development, including formatting dates, adding currency symbols, etc.; using filters in Vue2 is also relatively simple and easy to use. Let me briefly summarize the use of filters in Vue2;

  • global filter;
// main.js
Vue.filter('dateFormat', function (value) {
    
    
    // ...
    return newValue
})
  • component filter;
// xxx.vue
export default {
    
    
    filters: {
    
    
        dateFormat: function (value) {
    
    
            // ...
            return newValue
        }
    }
}

used in the component

<template>
	<div>
        <span>{
   
   { date | dateFormat }}</span>
    </div>
</template>

In Vue2, filters can be used in series, and the value received by each filter is the value returned before, for example:

{
   
   { date | dateFormat | dateFormat1 }}

Of course, the filter can also pass parameters, let's modify it a little:

// main.js
Vue.filter('dateFormat', function (value, format = 'yyyy-MM-dd hh:mm:ss') {
    
    
    switch (format) {
    
    
		// ...
    }
    return newValue
})
<!-- 
	这里的过滤器需要传入两个参数,第一个参数默认是需要过滤的值,这里也就是 date,第二个参数是我们自己传进去的值,这里是'yyyy-MM-dd hh:mm:ss'
-->
<span>{
   
   { date | dateFormat('yyyy-MM-dd hh:mm:ss') }}</span>

After summarizing the filters of Vue2, let’s take a look at the filters in Vue3. According to the official website documents, the filters are removed in Vue3 . The official recommendation is that we use computedor methodto replace the filters;

insert image description here

Of course, it doesn't mean that we can't use filters at all, we can mount them on the global instance object, and then call them $filtersdirectly or get the filter;

// main.js
app.config.globalProperties.$filters = {
    
    
    dateFormat: function (value) {
    
    
        // ...
        return newValue
    }
}
<template>
	<!-- 方式一 -->
	<span>{
   
   { $filters.dateFormat(date) }}</span>
	<!-- 方式二 -->
	<span>{
   
   { dateFormat(date) }}</span>
</template>
<script setup>
import { getCurrentInstance } from 'vue'
const { dateFormat } = getCurrentInstance().appContext.config.globalProperties.$filters
</script>

Guess you like

Origin blog.csdn.net/Ljwen_/article/details/127387736