在Vue JS中,从vue实例内部的方法调用过滤器


86

假设我有一个Vue实例,如下所示:

new Vue({
    el: '#app',

    data: {
        word: 'foo',
    },

    filters: {
       capitalize: function(text) {
           return text.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
       }
    },

    methods: {
        sendData: function() {
            var payload = this.$filters.capitalize(this.word); // how?
        }
    }
}

我可以轻松地在模板中使用过滤器,如下所示:

<span>The word is {{ word | capitalize }}</span>

但是,如何在实例方法或计算属性中使用此过滤器?(显然,该示例很简单,我的实际过滤器更复杂)。

Answers:



28

这对我有用

  1. 定义过滤器

    //credit to @Bill Criswell for this filter
    Vue.filter('truncate', function (text, stop, clamp) {
        return text.slice(0, stop) + (stop < text.length ? clamp || '...' : '')
    });
    
  2. 使用过滤器

    import Vue from 'vue'
    let text = Vue.filter('truncate')(sometextToTruncate, 18);
    

这个答案的缺陷在于,import Vue from 'vue'当一个变量存在时就依赖它并创建一个新变量。
Jay Bienvenu

3

您可以创建一个vuex类似于helper的函数,以将全局注册的过滤器映射到vue组件的methods对象中:

// map-filters.js
export function mapFilters(filters) {
    return filters.reduce((result, filter) => {
        result[filter] = function(...args) {
            return this.$options.filters[filter](...args);
        };
        return result;
    }, {});
}

用法:

import { mapFilters } from './map-filters';

export default {
    methods: {
        ...mapFilters(['linebreak'])
    }
}

1

如果您的过滤器是这样的

<span>{{ count }} {{ 'item' | plural(count, 'items') }}</span>  

这就是答案

this.$options.filters.plural('item', count, 'items')

0

为了补充Morris的答案,这是我通常用来在其中放入过滤器的文件示例,您可以在使用此方法的任何视图中使用。

var Vue = window.Vue
var moment = window.moment

Vue.filter('fecha', value => {
  return moment.utc(value).local().format('DD MMM YY h:mm A')
})

Vue.filter('ago', value => {
  return moment.utc(value).local().fromNow()
})

Vue.filter('number', value => {
  const val = (value / 1).toFixed(2).replace('.', ',')
  return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.')
})
Vue.filter('size', value => {
  const val = (value / 1).toFixed(0).replace('.', ',')
  return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.')
})

这是不是一个好主意申报物品在全球范围内,它windows.Vuewindows.moment不会,除非你绝对要,没有任何其他办法。
J.Ko

这个主题根本不对!每个项目的全局定义过滤器是一个好规则!
realtebo
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.