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

Vue全局属性$t在script标签中失效,报错this.$t is not a function

问题原因

props默认值的函数执行时机早于组件实例的创建阶段,此时this并不指向组件实例,自然无法访问到挂载在app.config.globalProperties上的$t方法。

Vue在解析组件props时,会优先处理默认值逻辑,这时候组件实例还未初始化完成,全局注入的$t等属性还没绑定到this对象上,所以调用this.$t会抛出“not a function”的错误。

解决方案

方案一:直接调用全局langService实例

既然langService是全局存在的,你可以直接导入它,调用其trans方法生成默认值,无需依赖组件实例的this:

// 替换为langService实际的导入路径
import langService from '@/path/to/langService';

export default {
  props: {
    placeholder: {
      type: String,
      default() {
        return langService._lang.trans('hello');
      },
    }
  }
}

方案二:在组件实例初始化后赋值

如果不想直接依赖langService,可以把默认值逻辑放到组件生命周期钩子(比如created)中执行,此时组件实例已创建完成,this.$t可正常使用:

export default {
  props: {
    placeholder: {
      type: String,
      default: undefined,
    }
  },
  data() {
    return {
      // 用内部data属性承接,避免直接修改props
      innerPlaceholder: this.placeholder,
    };
  },
  created() {
    if (!this.innerPlaceholder) {
      this.innerPlaceholder = this.$t('hello');
    }
  }
}

模板中改用内部属性:

<template>
  <input :placeholder="innerPlaceholder" />
</template>

内容的提问来源于stack exchange,提问作者Dr. Junior

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:31:21