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

2019-03-17 05:22发布

Say I have a Vue instance like so:

new Vue({
    el: '#app',

    data: {
        word: 'foo',
    },

    filters: {
       capitalize: function(text) {
           return text.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
       }
    },

    methods: {
        sendData: function() {
            var payload = this.$filters.capitalize(this.word); // how?
        }
    }
}

I can easily use the filter in a template like so:

<span>The word is {{ word | capitalize }}</span>

But how can I use this filter from within an instance method or computed property? (Obviously this example is trivial and my actual filters are more complex).

3条回答
你好瞎i
2楼-- · 2019-03-17 05:59

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);
    
查看更多
叼着烟拽天下
3楼-- · 2019-03-17 06:02
this.$options.filters.capitalize(this.word);

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

查看更多
霸刀☆藐视天下
4楼-- · 2019-03-17 06:14

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, '.')
})
查看更多
登录 后发表回答