假设我有一个像这样的 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?
}
}
}
我可以轻松地在模板中使用过滤器,如下所示:
<span>The word is {{ word | capitalize }}</span>
但是如何在实例方法或计算属性中使用此过滤器? (显然这个例子是微不足道的,我的实际过滤器更复杂)。
这对我有用
为这个过滤器定义过滤器 //credit to @Bill Criswell Vue.filter('truncate', function (text, stop,clamp) { return text.slice(0, stop) + (stop < text.length ? clamp || ' ...' : '') });使用过滤器 import Vue from 'vue' let text = Vue.filter('truncate')(sometextToTruncate, 18);
import Vue from 'vue'
并在一个已经存在的情况下创建一个新变量。
如果你的过滤器是这样的
<span>{{ count }} {{ 'item' | plural(count, 'items') }}</span>
这就是答案
this.$options.filters.plural('item', count, 'items')
您可以创建一个类似 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;
}, {});
}
用法:
import { mapFilters } from './map-filters';
export default {
methods: {
...mapFilters(['linebreak'])
}
}
reduce
方法的错误使用。结合使用 map
和 Object.entries
会更好。
为了补充莫里斯的答案,这是我通常用来在其中放置过滤器的文件示例,您可以使用此方法在任何视图中使用。
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, '.')
})
windows.Vue
和 windows.moment
会这样做,除非您绝对必须这样做,而没有任何其他方式。
尝试:
this.$options.filters.capitalize
不定期副业成功案例分享
this.$options
没有filters
属性。this.$root.$options.filters