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');
},
}
},
});
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.
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.
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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With