Javascript 在 Vue JS 中,从 vue 实例内部的方法中调用过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33639312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:17:29  来源:igfitidea点击:

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

javascriptvue.js

提问by harryg

Say I have a Vue instance like so:

假设我有一个像这样的 Vue 实例:

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).

但是如何从实例方法或计算属性中使用此过滤器?(显然这个例子是微不足道的,我的实际过滤器更复杂)。

回答by Moz Morris

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

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

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

回答by Olexiy Zamkoviy

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);
    
  1. 定义过滤器

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

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

回答by Ahmad Mobaraki

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

您可以创建一个vuex类似的辅助函数来将全局注册的过滤器映射到 vue 组件的方法对象中:

// 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'])
    }
}

回答by Kiko Seijo

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, '.')
})