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

How to apply a filter within a Vuejs component?

本文关键字:应用 过滤器 组件 Vuejs      更新时间:2023-09-26

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

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');
            },
        }
    },
});

它有点隐藏,我不确定它是否被记录在案,但是关于如何在组件中使用过滤器存在 Github 问题。

要使用 getter 和 setter,计算属性是完美的:

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>

筛选器只能具有组件的作用域(与指令或转换相同)。 您需要注册它组件级别。你在 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