Reputation: 387
I tried doing this, but it does not work.
// filter.js
export default {
converTimestamp: function (seconds) {
var date = new Date(seconds * 1000);
return date.toDateString();
}
};
// main.js
import customFilters from './store/filters';
Upvotes: 21
Views: 13440
Reputation: 3733
For Vue3
Create filters.js file:
const filters = {
upperCase(value) {
return value.toUpperCase();
}
}
export default filters;
import the file in main.js and use it globally with globalProperties
:
import { createApp } from 'vue';
import filters from './filters'
const app = createApp({});
app.config.globalProperties.$filters = filters;
Then you can use it directly in template, like that:
{{ $filters.upperCase('some text') }}
Upvotes: 2
Reputation: 1496
We can create a plugin for that:
// filters.js
import Vue from 'vue'
export function truncate( text, length, suffix = '...' ) {
if (text.length > length) {
return text.substring(0, length) + suffix;
} else {
return text;
}
}
export function json( value ) {
return JSON.stringify(value);
}
const filters = { truncate, json }
Object.keys( filters ).forEach( key => {
Vue.filter( key, filters[ key ] )
})
then add this new plugin in the config
export default {
plugins: ['~/plugins/filters.js']
}
Upvotes: 1
Reputation: 424
If you don't have so many filters, you can also define them in a single file:
// filters.js
export default {
filterA: () => {},
filterB: () => {},
}
And import them globally:
// main.js
import filters from './filters';
for(let name in filters) {
Vue.filter(name, filters[name]);
}
Upvotes: 10
Reputation: 34306
Here's an example:
// MyFilter.js
import Vue from 'vue';
Vue.filter('myFilter', value => {
return value.toUpperCase();
});
// main.js
import './MyFilter.js';
If you don't want to register the filters globally, you can do it like this:
// MyFilter.js
export default function (value) {
return value.toUpperCase();
}
// MyComponent.vue
import MyFilter from './MyFilter.js';
export default {
filters: {
MyFilter,
},
};
Upvotes: 69