如何在 Vue.js 中添加一堆全局过滤器? [英] How to add a bunch of global filters in Vue.js?
问题描述
我想在 Vue.js 应用程序中使用一些全局过滤器.我知道我需要在我的主要 Vue 实例之前定义它们,但是从代码组织的角度来看,将它们全部粘贴在main.js"文件中对我来说似乎并不合适.我怎么能在一个单独的文件中定义,导入到main.js"?无法完全理解为此导入/导出的内容.
I want to make use of a few global filters in a Vue.js app. I know I need to define them before my main Vue instance, but sticking them all in the 'main.js' file doesn't seem right to me from a code organisation point of view. How could I have the definitions in a separate file, imported to 'main.js'? Can't quite get my head around the import/export stuff for this.
推荐答案
创建一个 filters.js 文件.
Create a filters.js file.
import Vue from "vue"
Vue.filter("first4Chars", str => str.substring(0, 4))
Vue.filter("last4Chars", str => str.substring(str.length - 4))
将其导入您的 main.js.
Import it into your main.js.
import Vue from 'vue'
import App from './App'
import "./filters"
new Vue({
el: '#app',
template: '<App/>',
components: { App },
})
这是一个有效的示例.
旁注:如果您收到找不到 Vue"的消息错误类型,作为测试,尝试在 new Vue()
声明之后导入过滤器,如下所示:
Side note: If you get a "Vue not found" type of error, as a test try importing filters after the new Vue()
declaration, like this:
import Vue from 'vue'
import App from './App'
new Vue({
el: '#app',
template: '<App/>',
components: { App },
})
import "./filters"
这篇关于如何在 Vue.js 中添加一堆全局过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!