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

Vue模板同一全局翻译变量首次使用正常,第二次调用报this未定义错误

问题诱因

  1. Vue 模板的插值表达式默认无需显式声明 this,框架编译时会自动将表达式上下文绑定到当前组件实例,显式写 this 属于非规范写法,本身就存在上下文指向失效的风险。
  2. 你遇到的差异化报错是两个场景叠加导致的:
    • 第一个 {{ this.$root.translations['t_lei'] }} 包裹在带 v-if 的 <span> 标签内,属于独立的模板编译作用域块,上下文绑定正常;第二个和前面嵌套多层的超长三元运算处于同一个作用域块,模板编译器处理连续超长表达式时出现了上下文绑定偏移,导致执行时 this 指向丢失。
    • 当 item['service_price_discounted'] <= 0 时,第一个带 this 的 <span> 不会渲染,只有第二个 this 表达式执行,刚好命中绑定失效的场景触发报错。

修复方案

  • 直接删除所有模板插值表达式里的 this. 前缀,直接写 {{ $root.translations['t_lei'] }} 即可,Vue 会自动绑定到当前组件实例的 $root 属性,完全规避上下文指向问题。
  • 推荐优化:不要在模板里写多层嵌套的超长三元运算,抽成计算属性处理,既提升可读性,也能彻底避免模板编译异常:
// 组件计算属性
computed: {
  priceText() {
    const { service_price, service_price_max, service_price_discounted } = this.item
    const unit = this.$root.translations['t_lei']
    // 原价拼接逻辑
    let originPrice = service_price + (service_price_max > service_price ? `-${service_price_max}` : '')
    if (service_price_discounted > 0) {
      // 折扣价拼接逻辑
      let discountPrice = service_price_discounted
      if (service_price_max > service_price) {
        const discountRate = (service_price - service_price_discounted) / service_price
        discountPrice += `-${(discountRate * service_price_max).toFixed(2)}`
      }
      return { originPrice: `${originPrice} ${unit}`, discountPrice: `${discountPrice} ${unit}` }
    }
    return { originPrice: '', discountPrice: `${originPrice} ${unit}` }
  }
}
<!-- 模板简化后写法 -->
<div class="fashion-lounge-price">
  <h6>
    <span v-if="priceText.originPrice">{{ priceText.originPrice }}</span>
    {{ priceText.discountPrice }}
  </h6>
</div>

内容的提问来源于stack exchange,提问作者Răzvan T.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:06:02