Teach you two ways to use filters in VUE

This article is shared from HUAWEI CLOUD Community " Filter Usage in VUE ", author: Zhang Youbo - Zhang Youbo.

foreword

Vue.js allows us to customize filters that can be used for some common text formatting. Filters can be used in two places: double curly brace ({undefined{ }}) interpolation and v-bind expressions (the latter is supported since 2.1.0+). Filters should be added at the end of JavaScript expressions, indicated by the "pipe" symbol.

<!-- 在双花括号中 -->
<div>{{ message | capitalize }}</div>
 
<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | formatId"></div>
复制代码

1. Global filter

Defining a global filter is as simple as exporting a method.

It is very simple to use, you only need to introduce this filter globally in the entry file, and use Vue.filter(key, value) to introduce it.

For example, if the timestamp returned by the Java backend is accurate to seconds, while the timestamp in JS is expressed in milliseconds, you can define a global filter that converts the timestamp:

//main.js
import Vue from 'vue'
Vue.filter('millisecond', (value) => {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})
复制代码

In the components that need to be used use:

<div>{{1516101106 | millisecond}}</div>
复制代码

Single mount of global filters

/**
 * dateTmp:要过滤的值
 * fmtTmp:传入的参数,可接收多个参数
 */
<template>
   <!-- 2021-12-20 19:14:18 -->
  <div>{{ 1639998858000 | dateFormat("yyyy/MM/dd HH:mm:ss") }}</div>
</template>
 
Vue.filter('dateFormat', function (dateTmp, fmtTmp) {
  let fmt = fmtTmp
  let date = dateTmp
 
  if (!fmt) {
    fmt = 'yyyy.MM.dd'
  }
  if (!(date instanceof Date)) {
    date = new Date(date)
  }
  let o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, // 小时
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  }
  let week = {
    '0': '日',
    '1': '一',
    '2': '二',
    '3': '三',
    '4': '四',
    '5': '五',
    '6': '六'
  }
 
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '星期' : '周') : '') + week[date.getDay() + ''])
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return fmt
});
复制代码

Bulk Mounting of Global Filters

//定义方法
//filters.js
export function slice (temp,num) {
    return temp.slice(0,num);
}
复制代码
//挂载
//main.js
import * as filters from '@/assets/js/filters';
 
Object.keys(filters).forEach(key => {
    Vue.filter(key, filters[key]);
});
复制代码
//调用
<!-- 1234 -->
<div>{{ '123456' | slice(4) }} </div>
复制代码

2. Component filter

The component filter is simpler, just need filtersto , but it is only valid for this component.

For example, define a filter with the first letter capitalized:

//定义方法
export default {
  filters: {
    capitalize: function (value) {
      if (!value) return ''
      value = value.toString()
      return value.charAt(0).toUpperCase() + value.slice(1)
    }
  }
}
复制代码

example example

<template>
  <!-- 我要被过... -->
  <div>{{ msg | setSize }}</div>
</template>
 
<script>
export default {
  data() {
    return {
      msg: "我要被过滤",
    };
  },
  filters: {
    setSize(value) {
      if (value.length > 4) {
        return value.splice(0, 4) + "...";
      } else {
        return value;
      }
    },
  },
};
</script>
复制代码

Click Follow to learn about HUAWEI CLOUD's new technologies for the first time~

Guess you like

Origin juejin.im/post/7080344336134570015