Chris February 2016

How to apply a filter within a Vuejs component?

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

Answers


Ricardo February 2016

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


nils February 2016

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>

Post Status

Asked in February 2016
Viewed 3,325 times
Voted 13
Answered 2 times

Search




Leave an answer