过滤器无法访问 this,因其是纯函数且不绑定组件实例;需将 systemInfo、$t 等依赖作为参数传入,不可在 filter 内调用 uni API 或 this.$t。

不能获取。uni-app 的过滤器(Vue.filter)函数运行时**没有 this 上下文**,也不在组件实例作用域内,强行访问 this 会是 undefined 或报错。
为什么 filter 里拿不到 this
过滤器本质是纯函数,被 Vue 编译器在模板解析阶段调用,不绑定任何实例。它只接收管道符左边的值(value)和后续显式传入的参数(如 format),不自动注入 this、uni、$t 或任何响应式数据。
- 即使你在组件
data里定义了systemInfo,filter 内也访问不到this.systemInfo - 调用
uni.getSystemInfoSync()会报ReferenceError: uni is not defined(因为 filter 不在平台 API 注入环境) - 试图用
this.$t('xxx')做国际化,会直接抛TypeError: Cannot read property '$t' of undefined
想用系统信息或 i18n 怎么办
必须把依赖提前“准备好”,再作为参数传进 filter,而不是在 filter 内部动态获取。
- 在组件
data或computed中预先调用uni.getSystemInfoSync(),存为变量,模板中传入:{{ status | statusText(systemInfo.platform) }} - 状态文本映射若需多语言,不要在 filter 里调
this.$t,而应把翻译结果作为参数传入,比如:{{ code | statusText($t('statusMap')) }},其中$t('statusMap')返回一个对象{ '0': 'Normal', '1': 'Pending' } - 避免在 filter 中做异步操作(如
uni.getStorage),它无法 await,也不支持回调嵌套
常见错误写法及替代方案
以下写法全部无效:
Vue.filter('platformName', function(value) {
return this.systemInfo?.platform === 'ios' ? 'iOS' : 'Android' // ❌ this 是 undefined
})
正确做法是把平台标识作为参数传进来:
{{ 1 | statusText(systemInfo.platform) }}
// 对应 filter:
Vue.filter('statusText', (value, platform) => {
const map = {
ios: { '0': '正常', '1': '待审核' },
android: { '0': 'OK', '1': 'Pending' }
}
return map[platform]?.[value] || '未知'
})
真正容易被忽略的是:filter 的执行时机早于组件 mounted,甚至早于 onLoad,所以连“先赋值再使用”这种思路都不可靠——参数必须由模板明确提供,不能指望 filter 自己去“查”。


















