VUE开发--过滤器(十四)

一、过滤器

Vue.js 允许你自定义过滤器,可被用于一些常见的文本格式化。过滤器可以用在两个地方:双花括号插值和 v-bind 表达式 (后者从 2.1.0+ 开始支持)。过滤器应该被添加在 JavaScript 表达式的尾部,由“管道”符号指示:

<!-- 在双花括号中 -->
{{ message | capitalize }}

<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | formatId"></div>

1、在Vue中使用过滤器(Filters)来渲染数据是一种很有趣的方式。
2、首先我们要知道,Vue中的过滤器不能替代Vue中的methods、computed或者watch,
3、过滤器不改变真正的data,而只是改变渲染的结果,并返回过滤后的版本。
4、在很多不同的情况下,过滤器都是有用的,比如尽可能保持API响应的干净,并在前端处理数据的格式。
5、在你希望避免重复和连接的情况下,它们也可以有效地封装成可重用代码块背后的所有逻辑。
6、在Vue 2.0中已经没有内置的过滤器了,我们可以自定义过滤器。

二、定义过滤器

  1. 定义本地的过滤器
    本地过滤器被注册到一个Vue组件中。
    将字母变成大写:
<template>
  <div class="container">
    <h1>{{ msg | Upper }}</h1>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  filters: {
    Upper: function(value) {
      if (!value) return "";
      value = value.toString();
      return value.charAt(0).toUpperCase() + value.slice(1);
    }
  },
  data() {
    return {
      msg: "computer"
    };
  }
};
</script>
  1. 在创建 Vue 实例之前全局定义过滤器
    在价格前面加上美元符号:
// 声明一个全局的过滤器 
Vue.filter('toUSD', function (value) { 
  return `$${value}` 
}) 
// 在模板中这样使用 文本插值的使用方式 
<div id="app"> 
    <h1>{{ price | toUSD}}</h1>
 </div>

注意:过滤器定义必须始终位于Vue实例之上。

  1. 有参过滤器
//date.js
export function formatDate (date, fmt) {
      if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
           }
    let o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
        let str = o[k] + ''
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
      }
    }
      return fmt
    }
    function padLeftZero (str) {
      return ('00' + str).substr(str.length)
    }

定义过滤器:

<template>
  <div class="container">
    <p>
      <b>
      {{new Date() | FormatDate('yyyy-MM-dd hh:mm')}}</b>
    </p>
  </div>
</template>

<script>
import {formatDate} from "../common/date.js"
export default {
  name: "HelloWorld",
  filters: {
    /* 格式化时间*/
    FormatDate: function(date, type) {
      console.log(date + "," + type);
      return formatDate(date, type);
    }
  }
  }
};
</script>

  1. 格式化时间戳

<template>
  <div class="container">
    <p><b>{{ 1533527037000 | formatDate }}</b></p>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  filters: {
    /* 格式化时间戳 */
    formatDate(val) {
      const date = new Date(val);
      const year = date.getFullYear();
      const month =
        date.getMonth() > 9 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`;
      const day =
        date.getDate() > 9 ? date.getDate() + 1 : `0${date.getDate() + 1}`;
      return `${year}-${month}-${day}`;
      console.log(val);
    }
  },
  data() {
    return {
      msg: "computer"
    };
  }
};
</script>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容