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

2022-08-30 04:07:14

假设我有一个 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>

但是,如何从实例方法或计算属性中使用此筛选器?(显然,这个例子是微不足道的,我的实际过滤器更复杂)。


答案 1
this.$options.filters.capitalize(this.word);

查看 http://vuejs.org/api/#vm-options


答案 2

这对我有用

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