Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vue JS, call a filter from a method inside the vue instance

People also ask

Where do I put the Vue filter?

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 do you call a Vue method?

We can call a Vue. js method on page load by calling it in the beforeMount component hook. We can also make a method run on page load by calling it in the created hook. And we can do the same in the mounted hook.

What does $t mean in Vue?

Vuex is a state management pattern for vue. js. $t is the injected method from vue. js or Vue. i18n.


this.$options.filters.capitalize(this.word);

See http://vuejs.org/api/#vm-options


This is what worked for me

  1. Defining filter

    //credit to @Bill Criswell for this filter
    Vue.filter('truncate', function (text, stop, clamp) {
        return text.slice(0, stop) + (stop < text.length ? clamp || '...' : '')
    });
    
  2. Using filter

    import Vue from 'vue'
    let text = Vue.filter('truncate')(sometextToTruncate, 18);
    

if your filter is something like this

<span>{{ count }} {{ 'item' | plural(count, 'items') }}</span>  

this is the answer

this.$options.filters.plural('item', count, 'items')

You can create a vuex like helper function to map globally registered filters into the methods object of a vue component:

// map-filters.js
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'])
    }
}

To complement Morris answer, this is an example of a file I normally use to put filters inside, you can use in any view using this method.

var Vue = window.Vue
var moment = window.moment

Vue.filter('fecha', value => {
  return moment.utc(value).local().format('DD MMM YY h:mm A')
})

Vue.filter('ago', value => {
  return moment.utc(value).local().fromNow()
})

Vue.filter('number', value => {
  const val = (value / 1).toFixed(2).replace('.', ',')
  return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.')
})
Vue.filter('size', value => {
  const val = (value / 1).toFixed(0).replace('.', ',')
  return val.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.')
})