Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
            },
        }
    },
});
like image 312
Chris Avatar asked Feb 08 '16 09:02

Chris


People also ask

Where do you put Vue filters?

Going off number 2, because VueJS filters are meant for text transformations, they can only be used in two places: mustache interpolations (the curly braces in your template) and in v-bind expressions.

How many ways are there to define a filter in VueJS?

The global filter is available in all filters, and the local filter is defined only in the component. A filter is essentially a function that takes through value, does manipulation, and then displays processed values. The Vue component can be created in four different ways: New Vue.

What does $Set do in Vue?

js $set() method to set data object properties. Binding a class on an item and controlling it by the truthy value of a data property is a powerful feature of Vue.


2 Answers

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>
like image 62
nils Avatar answered Sep 21 '22 08:09

nils


You can add local filters to each component:

filters: {
  filterName: function (value) {
    // some logic
    var result = ....
    // 
    return result;
  }
}

call that filter:

<div> {{ value | filterName }} </div>
like image 24
Samir Rahimy Avatar answered Sep 18 '22 08:09

Samir Rahimy