How to apply a filter within a Vuejs component?

2019-04-29 03:35发布

If I have a simple filter, say:

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

And a simple component:

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

And within the markup:

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

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

Something like:

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

2条回答
干净又极端
2楼-- · 2019-04-29 03:41

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.

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

And the corresponding markup:

<example inline-template :msg="My foo is full of foo drinks!">
    {{ useMsg }}
</example>
查看更多
来,给爷笑一个
3楼-- · 2019-04-29 03:44

A filter can have the scope of a component only (same as directives or transitions). you need to register it component level. You have a pretty good example at the VueJS docs

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

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

Hope this helps. The information can be found at: http://vuejs.org/guide/components.html#Local_Registration

查看更多
登录 后发表回答