filters在小程序端完全失效,因平台不支持管道语法解析;应改用computed属性或methods函数返回标签对象,确保跨平台一致性。

过滤器在 uni-app 里不能“快速生成”折扣标签——它根本不会生效,尤其在小程序端。你写 {{ price | discountLabel }},真机上大概率什么也不显示。
为什么 filters 在小程序里基本失效
uni-app 的 filters 是 Vue 2 时代的遗留机制,编译到微信/支付宝/字节等小程序时,底层不支持管道语法解析。H5 端可能侥幸跑通,但其他平台一律忽略。这不是写法问题,是平台能力缺失。
- 微信小程序基础库 2.20+ 仍无
filter执行环境 -
Vue.filter()只注入到 Vue 实例原型,而小程序渲染层不走 Vue 的 template compiler - 即使你在
main.js注册了 filter,pages/index/index.vue模板里调用也无效
真正能用的替代方案:计算属性 + 条件 class
折扣标签本质是「根据原价、现价、是否打折」三个状态决定文案和样式,用 computed 或 methods 直接返回对象更可控:
computed: {
discountTag() {
const { originalPrice, price } = this.goodsItem
if (originalPrice > price && price > 0) {
const discount = Math.round((price / originalPrice) * 10)
return {
text: `${discount}折`,
type: 'sale'
}
}
return { text: '新品', type: 'new' }
}
}
模板里直接绑定:
<view class="tag" :class="'tag--' + discountTag.type">{{ discountTag.text }}</view>
- 避免字符串拼接逻辑塞进模板,可读性高
- 所有平台一致运行,无兼容性风险
- 后续加“满减叠加标识”“会员专享标”也只需扩 compute 逻辑
如果坚持用函数封装,注意这三点
把折扣逻辑抽成工具函数没问题,但别叫它“filter”。调用时必须显式执行:
- 不要在模板里写
{{ goodsItem | getDiscountTag }}(无效) - 改用
{{ getDiscountTag(goodsItem) }},并在methods或setup中定义该函数 - 函数内部别依赖
this或响应式上下文,确保纯函数特性,方便单元测试
例如:
methods: {
getDiscountTag(item) {
if (!item.originalPrice || !item.price) return ''
const ratio = item.price / item.originalPrice
if (ratio <p>折扣标签看似简单,但跨平台一致性比“写得快”重要得多。别被 Vue 2 文档带偏,小程序里没有 magic pipe。</p>










