zoukankan      html  css  js  c++  java
  • vue-cli 自定义过滤器的使用

    vue-cli 自定义过滤器的使用

    vue2.0将内置过滤器去除,所以过滤器需要自己编写。

    Vue.js 允许你自定义过滤器,可被用作一些常见的文本格式化。过滤器可以用在两个地方:mustache 插值和 v-bind 表达式。过滤器应该被添加在 JavaScript 表达式的尾部,由“管道”符指示:

    {{ message | capitalize }}
    
    <div v-bind:id="rawId | formatId"></div>

    步骤:

      第一步:编写过滤器文件如(filter.js),我们可以src文件夹中新建文件夹,来存放filter.js文件

      

      在filter.js文件夹中,代码如下: 
      首先 import Vue from 'vue',之后就可以自己编写过滤器了

    import Vue from 'vue'
    /**
     * 货币格式化
     * currencyType 货币符号
     */
    
    Vue.filter('formatPrice', function(value = '0', currencyType = '') {
      let res;
      if (value.toString().indexOf('.') === -1) {
        res = (value || 0).toString().replace(/(d)(?=(?:d{3})+$)/g, '$1,') + '.00'
      } else {
        let prev = value.toString().split('.')[0]
        let next = value.toString().split('.')[1] < 10 ? value.toString().split('.')[1] + '0' : value.toString().split('.')[1]
        res = (prev || 0).toString().replace(/(d)(?=(?:d{3})+$)/g, '$1,') + '.' + next
      }
      return currencyType + res
    })
    

           代码中formatPrice为过滤器名称,之后function的括号中为传入的需要过滤的数据,return返回处理后的值即可。

       第二步:在main.js文件中引入filter.js

    import fliter from './api/filter'
    

      

      第三步:在组件中使用过滤器,直接使用过滤器函数名,就会在页面上渲染了

    <li>{{123456.4 | formatPrice}}</li>
    

    附:data数据处理过滤器

    /Date(1332919782070)/ ====>   2018-6-20
    Vue.filter('dateFormat', function(val) {
      if (val != null) {
        var date = new Date(parseInt(val.replace("/Date(", "").replace(")/", ""), 10));
        //月份为0-11,所以+1,月份小于10时补个0
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        return date.getFullYear() + "-" + month + "-" + currentDate;
      //返回年-月-日 2015-6-20 } return "" });
     new Data() ====>2018-6-20   (主要用于js获取的当前系统时间的处理)
    Vue.filter('jsDateFormat', function(val) {
      if (val != null) {
        var month = val.getMonth()+1
        return val.getFullYear() + "-" +month+ "-" +  val.getDate();
      }
      return ""
    });
    

      

    参考资料:https://blog.csdn.net/shuihuanhuan/article/details/75417577

  • 相关阅读:
    011 Go语言基础之map
    009 Go语言基础之切片
    计算机组成原理 — GPU 图形处理器
    js 实现各浏览器全屏
    js 实现各浏览器全屏
    IIS-真正解决ASP.NET每一个页面首次访问超级慢的问题
    IIS-真正解决ASP.NET每一个页面首次访问超级慢的问题
    首次启动速度慢的问题记录IIS性能优化
    首次启动速度慢的问题记录IIS性能优化
    C#-执行cmd命令,获取结果
  • 原文地址:https://www.cnblogs.com/s313139232/p/9202859.html
Copyright © 2011-2022 走看看