简体   繁体   English

将 Vue 过滤器显式导入组件

[英]Explicitly import Vue filters into component

I have a global filters file, and I am trying to explicitly import just one filter into a component.我有一个全局过滤器文件,我试图将一个过滤器显式导入到组件中。

In my filters file, I have:在我的过滤器文件中,我有:

//filters.js
import Vue from 'vue';
Vue.filter('shorten', (str, len) => (str.length > len ? `${str.substring(0, len)}...` : str));
Vue.filter('secToMin', (dur) => Math.ceil (dur / 60));

and then in my component, I'd like to do something like:然后在我的组件中,我想做类似的事情:

//MyComponent.vue
import secToMin from './util/filters.js';
export default {
 filters: {
   secToMin: { secToMin, },
 },
};

But this does not actually fire the filters.但这实际上并没有触发过滤器。 Is it possible to do something like this??有可能做这样的事情吗?

You can export the filters as named exports:您可以将过滤器导出为命名导出:

export function shorten (str, len) {
  return str.length > len ? `${str.substring(0, len)}...` : str;
}

export function secToMin (dur) {
  return Math.ceil(dur / 60);
}

Then in your component:然后在您的组件中:

import { secToMin } from './util/filters.js';

export default {
 filters: {
   secToMin
 }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM