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

标签 javascript vue.js

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

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 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>

关于javascript - 如何在 Vuejs 组件中应用过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266157/

相关文章:

javascript - 使用 Zippopotam.us 的 JSON 结果作为 Google map 坐标

javascript - 将 UTF-8 编码的 JSON 从 DB 解析为 JS

javascript - 可折叠 Accordion 组件中的 Vue 加载组件

vue.js - 如何通过 Composition API 在 vue-chartjs 中使用 ChartOptions

vue.js - vuejs属性中的语法 `${k}`是什么?

apache - Directus api 和应用程序与前端在同一台服务器上

javascript - 如果登录应用程序如何重定向

javascript - 如何获得真实的 IFRAME 加载高度/宽度以及所有渲染图片的自然尺寸

javascript - 设置 html 表格中每行的列数限制

vue.js - Vuejs 3 中的 defineAsyncComponent