如何在 Vuejs 组件中应用过滤器?

How to apply a filter within a Vuejs component?

如果我有一个简单的过滤器,请说:

Vue.filter('foo', function (value) {
    return value.replace(/foo/g, 'bar');
});

还有一个简单的组件:

Vue.component('example', {
    props: {
        msg: String,
    },
});

在标记内:

<example inline-template :msg="My foo is full of foo drinks!">
    {{ msg }}
</example>

我可以简单地应用过滤器:

<example inline-template :msg="My foo is full of foo drinks!">
    {{ msg | foo }}
</example>

我可以轻松地在模板中应用过滤器,但是我想将该逻辑移回到组件中。

不需要成为过滤器,但基本上是一种为数据字段创建getter和setter的方法。

类似于:

Vue.component('example', {
    props: {
        msg: {
            type: String,
            getValue: function(value) {
                return value.replace(/foo/g, 'bar');
            },
        }
    },
});

过滤器只能具有组件的范围(与指令或转换相同)。您需要在组件级别注册它。您在 VueJS 文档中有一个很好的示例

var Child = Vue.extend({ /* ... */ })

var Parent = Vue.extend({
  template: '...',
  components: {
    // <my-component> will only be available in Parent's template
    'my-component': Child
  }
})

希望这对您有所帮助。可以在以下位置找到信息:http://vuejs.org/guide/components.html#Local_Registration

它有点隐藏,我不确定它是否被记录在案,但有一个 Github issue on how to use filters in components

要使用 getter 和 setter,computed properties 是完美的:

Vue.component('example', {
    props: {
        msg: {
            type: String,
        }
    },
    computed: {
        useMsg: {
            get: function() {
                return this.$options.filters.foo(this.msg);
            },
            set: function(val) {
                // Do something with the val here...
                this.msg = val;
            },
        },
    }
});

以及相应的标记:

<example inline-template :msg="My foo is full of foo drinks!">
    {{ useMsg }}
</example>

您可以为每个组件添加本地过滤器:

filters: {
  filterName: function (value) {
    // some logic
    var result = ....
    // 
    return result;
  }
}

调用那个过滤器:

<div> {{ value | filterName }} </div>