-
Notifications
You must be signed in to change notification settings - Fork 17
Is it possible to call a filter from JS? #405
Comments
I'd say this filter does not belong to the component then and should be refactored into a separate function, so that it can be reused in other places. |
Well, it belongs, it is used in JS only inside the component and nowhere else is planned to use it. |
Let me show what I mean (assuming CommonJS): function formatSize(size) { ... }
module.exports = Vue.extend({
...,
methods: {
doSomething: function() {
var size = ...;
var formatedSize = formatSize(size);
...
},
},
filters: {
formatSize: formatSize,
},
}); |
Yes, thank you very much, Denis. This is surely reasonable. But the question is still actual—is there a way to call a local filter from JS—we can detach the question from my example if you want. :) |
It's a bit verbose, but you can access it as |
Great! Thank you for the answer! |
If anyone is interested, I've written a small helper function to map globally registered filters into the methods object of a vue component (it's heavily influenced by vuex' export function mapFilters(filters) {
return filters.reduce((result, filter) => {
result[filter] = function(...args) {
return this.$options.filters[filter](...args);
};
return result;
}, {});
} Usage: import { mapFilters } from './map-filters';
export default {
methods: {
...mapFilters(['linebreak'])
}
} This is only useful when you have globally registered filters that you also want to use as a component method within javascript. Note that, often, a computed property is the better choice :) |
Vue.options.filters.xxx |
For global filters, first set: |
Hello!
I found that the global filter can be obtained (and then used) through Vue.filter('filterName').
But what for a local filter contained in some particular Vue instance? How is it possible to call it?
In my case, I have a filter which formats file size (KB, MB, etc.) I use it to display file size:
{{ file.size | formatSize }}
and I want to use the same filter to alert some message to a user. Of course, I can add method instead of filter, and use it, or create method + filter (which calls this method). But actually this is purely a filter, and I just need to call it from JS.
Thank you!
The text was updated successfully, but these errors were encountered: