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

har*_*ryg 54 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?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<span>The word is {{ word | capitalize }}</span>
Run Code Online (Sandbox Code Playgroud)

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

Moz*_*ris 134

this.$options.filters.capitalize(this.word);
Run Code Online (Sandbox Code Playgroud)

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

  • 在 NuxtJS 中使用 ```this.$root.$options.filters``` (10认同)
  • 你...美丽! (5认同)
  • 这在 Nuxt 上下文中对我不起作用。`this.$options` 没有 `filters` 属性。 (3认同)

Uyg*_*gar 11

如果你的过滤器是这样的

<span>{{ count }} {{ 'item' | plural(count, 'items') }}</span>  
Run Code Online (Sandbox Code Playgroud)

这就是答案

this.$options.filters.plural('item', count, 'items')
Run Code Online (Sandbox Code Playgroud)


小智 10

这就是对我有用的

  1. 定义过滤器

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

    import Vue from 'vue'
    let text = Vue.filter('truncate')(sometextToTruncate, 18);
    
    Run Code Online (Sandbox Code Playgroud)


Ahm*_*aki 5

您可以创建一个vuex类似的辅助函数来将全局注册的过滤器映射到 vue 组件的方法对象中:

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

用法:

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

export default {
    methods: {
        ...mapFilters(['linebreak'])
    }
}
Run Code Online (Sandbox Code Playgroud)