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

Vue2动态注入组件到DOM时vue-i18n报错$t/_t未定义如何解决

报错原因

你手动实例化动态组件时没有关联当前Vue组件树的上下文,vue-i18n注入的$t方法依赖实例上挂载的i18n内部属性_t,独立创建的空组件实例不存在这个属性,因此触发报错。

解决方案

实例化动态组件时传入当前父实例,让动态组件继承上下文的所有全局注入属性,修改后的代码如下:

const component = Vue.component('add-new-channel', {
  template: '<div class="add-new-channel"> <a-go-to-add-channel/></div>',
  components: { AGoToAddChannel }
});
// 核心修改:传入parent参数绑定当前父实例上下文
const mounted = new component({
  parent: this
  // 若继承上下文失效,可手动传入i18n实例,二选一即可
  // i18n: this.$i18n
}).$mount();
const $element = mounted.$el;
this.$nextTick(() => {
  const listEl = this.$refs.parent.querySelector('.tabs li:last-child');
  if (listEl) {
    listEl.appendChild($element);
  }
});

// 新增销毁逻辑,避免内存泄漏
this.$once('hook:beforeDestroy', () => {
  mounted.$destroy();
  $element.remove();
})
注意事项
  • 如果你的项目还用到了Vuex、Vue Router等插件,传入parent: this后动态组件也会自动继承$store、$route等属性,无需额外配置。
  • 动态插入的DOM不受Vue模板渲染逻辑管控,必须在父组件销毁时手动销毁动态组件实例并移除DOM节点,否则会造成内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:27:02