以插件库模式使用vue-i18n

问题描述 投票:0回答:1

您好,我正在使用vue3/rollup的库模式开发一套UI组件。一切都构建到本地 npm 包中。我们的想法是拥有一组可在多个项目中使用的 .vue 文件。

我的库项目包含多个 .vue 文件,当我不使用翻译时一切正常。我假设所有可能使用我的库的应用程序也将使用 vue-i18n。因此,我尝试通过标签将翻译添加到我的 .vue 文件中,并从 use-i18n 导入 t,假设执行文件时应用程序中会有 i18n 上下文,但没有任何效果...我已经对在库模式上下文中使用 vue-i18n 进行了大量研究,但我不断回到同一问题,即将 i18n 插件添加到应用程序中,但在我的库项目中我没有有一个创建应用程序...

UI 库 >index.ts

import type { App } from "vue";
import { provide } from "vue";
import Hello from "./Hello.vue";

export function createBusinessComponent() {
    const install = (app: App) => {
        app.component("Hello", Hello);
    };

    return { install };
}

UI 库 > Hello.vue

<template>
 <p>{{ t('hello') }}</p>
</template>

<script lang="ts">
  import { defineComponent } from "vue";
 
  import { useI18n,  } from "vue-i18n";

  export default defineComponent({
    setup: (props, { emit }) => {
      const { t } = useI18n();
      return {
        t,
      };
    },
  });
</script>
<i18n>{
    "en": {
        "hello": " Hello world",
    },
    "fr": {
        "hello": " Bonjour",
    }   
}</i18n>

我用 rollup 构建了所有东西,效果很好。我将构建包添加到应用程序项目的 package.json 中

我的应用程序 > main.ts

import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
import i18n from './i18n'
import router from './router'

import { createBusinessComponent } from 'ui-library'

const businessComp = createBusinessComponent({})

const app = createApp(App)
app.use(createPinia())
app.use(i18n)
app.use(router)
app.use(businessComp)
app.mount('#app')

我的应用程序 > i18n.ts(也使用应用程序中的翻译)

import { createI18n } from 'vue-i18n'
import EN from '../assets/props/en.json'
import FR from '../assets/props/fr.json'

const translations = {
  en: EN,
  fr: FR,
}

export default createI18n({
  legacy: false,
  locale: 'en',
  fallbackLocale: 'en',
  globalInjection: true,
  messages: translations,
})

我的应用程序 > App.vue

<template>
   <hello></hello>
</template>

Web 控制台中出现错误

语法错误:必须在

setup
函数的顶部调用(位于index-6cfa2a26.js:70354:94) 在 h6 (index-6cfa2a26.js:70354:94) 在 Lh (index-6cfa2a26.js:71311:10) 在 ql (index-6cfa2a26.js:71804:11) 设置时(index-6cfa2a26.js:73154:12) 在 callWithErrorHandling (runtime-core.esm-bundler.js:6656:22) 在 setupStatefulComponent (runtime-core.esm-bundler.js:6272:29) 在 setupComponent (runtime-core.esm-bundler.js:6228:11) 在 mountComponent (runtime-core.esm-bundler.js:4081:13) 在 processComponent (runtime-core.esm-bundler.js:4056:17) 在补丁(runtime-core.esm-bundler.js:3651:21)

我确信我不是第一个想在 i18n 中使用库模式的人,但我找不到任何东西......

vue.js vuejs3 internationalization rollupjs vue-i18n
1个回答
0
投票

更改Hello.vue文件直接使用setup语法糖

<template>
 <p>{{ t('hello') }}</p>
</template>

<script lang="ts" setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n();
</script>
© www.soinside.com 2019 - 2024. All rights reserved.