[Vuejs]-How can I access one attached filter from another in Vue

0πŸ‘

βœ…

one option is to seperate definition and global registration

(plus its now usable/importable in non-vue context)

// ie. in filters.js
export const formatDateTime = value => value 
  ? moment(String(value)).format('DD-MMM-YY hh:mm') 
  : null

export const getActivity = value => !value.lastvisited
  ? 'Not visited yet' 
  : 'Last logged in ' + formatDateTime(value.lastvisited)

// ie. in in a filter-global-registration.js
import { getActivity, formatDateTime } from 'filters.js'

Vue.filter('formatDateTime', formatDateTime);
Vue.filter('getActivity', getActivity)

0πŸ‘

What I usually do is create a global reference to your main Vue object, like:

// Create a filter which calls another filter.
Vue.filter('myFilter', () => {
    window.Vue.$options.filters.myOtherFilter(...);
});

// Initialize the main Vue object.
window.Vue = new Vue({

});

Then, you should be able to access your filters using window.Vue.$options.filters.myOtherFilter() inside of your filter functions.

It might not be ideal but it has helped me out on several occasions where you have to define plugins/services/components that dont give you the current Vue instance it uses.

Leave a comment