You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel+Inertia+Vue3项目中添加全局过滤器

正确全局过滤器添加方案

Vue3 已移除 Vue2 版本中原生支持的filter全局配置语法,推荐通过全局属性挂载的方式实现等价功能,以下是适配你现有Inertia配置的修改方案:

方案1:官方推荐的全局属性挂载(推荐)

在app.js中按如下方式修改代码:

// 提前定义所有需要的全局过滤器函数
const filters = {
  // 示例:金额格式化,保留2位小数
  formatMoney: (value) => {
    return Number(value).toFixed(2)
  },
  // 示例:日期格式化
  formatDate: (timestamp) => {
    return new Date(timestamp).toLocaleDateString('zh-CN')
  }
}

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => require(`./Pages/${name}.vue`),
    setup({el, app, props, plugin}) {
        const vueApp = createApp({render: () => h(app, props)})
            .use(plugin)
            .mixin({methods: {route}})

        // 批量挂载全局过滤器到Vue实例全局属性
        vueApp.config.globalProperties.$filters = filters

        return vueApp.mount(el);
    },
});

组件内调用方式:

  • 模板中直接调用:
<div>{{ $filters.formatMoney(100) }}</div>
  • 选项式API script中调用:
this.$filters.formatMoney(200)
  • 组合式API script中调用:
import { getCurrentInstance } from 'vue'
const { $filters } = getCurrentInstance().proxy

方案2:全局Mixin挂载(使用更便捷)

如果希望和Vue2过滤器用法一致,直接在模板中调用方法名,可通过全局Mixin实现:

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => require(`./Pages/${name}.vue`),
    setup({el, app, props, plugin}) {
        return createApp({render: () => h(app, props)})
            .use(plugin)
            .mixin({
                methods: {
                    route,
                    // 直接把过滤器方法定义在全局mixin的methods里
                    formatMoney(value) {
                        return Number(value).toFixed(2)
                    },
                    formatDate(timestamp) {
                        return new Date(timestamp).toLocaleDateString('zh-CN')
                    }
                }
            })
            .mount(el);
    },
});

调用方式:

<div>{{ formatMoney(100) }}</div>

内容的提问来源于stack exchange,提问作者Ahmed Yehia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 19:36:00