在 scr 目录下建立 filter 文件夹, 在文件价中新建文件 filter.JS
我们可以将过滤器写在该文件夹下
- export function firstFilter(value,dict){
- return dict[value] ? dict[value]:value
- }
接着我们在 main.JS 中注册全局过滤器, 加入如下代码
- import * as filters from './filter/filter'
- Object.keys(filters).forEach(key => {
- vue.filter(key, filters[key])
- })
这样我们就注册完了我可以在任意组件中直接使用这个过滤器
在 test.vue 中
- <template>
- <div>
- <el-input v-model="testVal"/><br/>
- {{testVal|firstFilter(dic)}}//testVal 会作为第一个参数直接传入
- </div>
- </template>
- <script>
- export default {
- data(){
- return{
- testVal: ' ',
- dic:{// 一般是传入
- 1:'first',
- 2:'secound'
- }
- }
- }
- }
- </script>
- <style>
- </style>
输入 1 输出 first
来源: http://www.bubuko.com/infodetail-3448374.html