如何在Vuejs组件中应用过滤器? [英] How to apply a filter within a Vuejs component?

查看:384
本文介绍了如何在Vuejs组件中应用过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a simple filter, say:

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>

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

I can simply apply the filter as such:

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

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

I can easily apply a filter within the template, however I want to move that logic back into the component.

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

It doesn't need to be a filter, but basically a way to create a getter and setter for data fields.

类似于:

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


推荐答案

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

It is slightly hidden and I'm not sure if it is documented, but there is a Github issue on how to use filters in components.

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

To use getters and setters, computed properties are perfect:

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>

这篇关于如何在Vuejs组件中应用过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆