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

时间:2015-11-10 20:47:26

标签: javascript vue.js

假设我有一个像这样的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>

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

5 个答案:

答案 0 :(得分:97)

this.$options.filters.capitalize(this.word);

See http://vuejs.org/api/#vm-options

答案 1 :(得分:5)

这是对我有用的

  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);
    

答案 2 :(得分:2)

如果您的过滤器是这样的

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

这就是答案

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

答案 3 :(得分:0)

您可以创建一个辅助函数,以将全局注册的过滤器映射到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'])
    }
}

答案 4 :(得分:-2)

为了补充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, '.')
})
相关问题