新建filter文件
src目录下新建filters目录,filters目录里新建index.js文件
exports.formatMoney = (value) => {if (value) {value = Number(value);return '¥ ' + value.toFixed(2);}};exports.statusName = (val) => {let statusName = '';switch (val) {case 0: {statusName = '已取消';break;}case 10: {statusName = '未付款';break;}case 20: {statusName = '已付款';break;}}return statusName;};
main.js里注册filter
import filters from './filters';Object.keys(filters).forEach(k => Vue.filter(k, filters[k]));注册filter后main如下import Vue from 'vue'import App from './App'import router from './router'import Mixin from './mixins';import filters from './filters';Vue.mixin(Mixin);Vue.config.productionTip = falseObject.keys(filters).forEach(k => Vue.filter(k, filters[k]));/* eslint-disable no-new */new Vue({el: '#app',router,components: { App },template: '<App/>'})
使用
<template><div><p>这是index页面</p><p @click="loadPage('Index')">Index</p><p @click="loadPage('About')">About</p><p @click="loadPage('Product')">Product</p><div>价格:{{price|formatMoney}}</div><div>订单状态:{{orderStatus | statusName}}</div></div></template><script>export default{data(){return{price:95,orderStatus:10}}}</script><style></style>
页面展示结果
这是index页面
Index
About
Product
价格:¥ 95.00
订单状态:未付款
如果觉得《vue 项目中 自定义过滤器 全局使用 filter》对你有帮助,请点赞、收藏,并留下你的观点哦!