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

Chr*_*ris 9 javascript vue.js

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

Vue.filter('foo', function (value) {
    return value.replace(/foo/g, 'bar');
});
Run Code Online (Sandbox Code Playgroud)

还有一个简单的组件:

Vue.component('example', {
    props: {
        msg: String,
    },
});
Run Code Online (Sandbox Code Playgroud)

在标记内:

<example inline-template :msg="My foo is full of foo drinks!">
    {{ msg }}
</example>
Run Code Online (Sandbox Code Playgroud)

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

<example inline-template :msg="My foo is full of foo drinks!">
    {{ msg | foo }}
</example>
Run Code Online (Sandbox Code Playgroud)

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

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

就像是:

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

nil*_*ils 13

它有点隐藏,我不确定它是否有文档记录,但是如何在组件中使用过滤器存在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;
            },
        },
    }
});
Run Code Online (Sandbox Code Playgroud)

和相应的标记:

<example inline-template :msg="My foo is full of foo drinks!">
    {{ useMsg }}
</example>
Run Code Online (Sandbox Code Playgroud)


Sam*_*imy 8

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

filters: {
  filterName: function (value) {
    // some logic
    var result = ....
    // 
    return result;
  }
}
Run Code Online (Sandbox Code Playgroud)

调用该过滤器:

<div> {{ value | filterName }} </div>
Run Code Online (Sandbox Code Playgroud)