【问题标题】:using i18n in Vue typescripte在 Vue 打字稿中使用 i18n
【发布时间】:2021-06-02 21:27:01
【问题描述】:

在VUE上学习TS的时候遇到了这样一个问题

我有一个用于渲染菜单的组件,我在其中连接数据

...
import ArrowRoundedDown9x6Svg from '~/svg/arrow-rounded-down-9x6.svg'
import headerNavigation from '~/data/headerNavigation'

@Component({
    components: { AppLink, Megamenu, Menu, ArrowRoundedDown9x6Svg }
})
export default class NavLinks extends Vue {
    items: INav = headerNavigation
    hoveredItem: INavLink | null = null
...

我在里面连接数据

import headerNavigation from '~/data/headerNavigation'

但是,在这个文件中我需要连接 i18n 来切换语言,我不知道该怎么做。里面没有构造函数

import { INav } from '~/interfaces/menus/nav'
import { TranslateResult } from 'vue-i18n'   // I create import 

const dataHeaderNavigation: INav = [
{
    title: "Home"
    url: '/',
}
export default dataHeaderNavigation

如果我尝试这样做,我会收到错误

const dataHeaderNavigation: INav = [
{
    title: this.TranslateResult.get("header.links.Home").subscribe(value => { this.Home= value });
           ^^^
    url: '/',
}

Error: Object is possibly 'undefined'.

en.json

{
    "header": {
        "links": {
            "Home": "Home Page"
        }
    }
}

如何正确链接到翻译后的元素?

【问题讨论】:

    标签: typescript vue.js vue-i18n nuxtjs


    【解决方案1】:

    需要添加一个Vue实例

    import Vue from 'vue'
    import { INav } from '~/interfaces/menus/nav'
    const dataHeaderNavigation: (vue: Vue) => INav = vue => [
        {
            title: vue.$t('header.menu.home'),
            url: '/'
        }]
    

    还需要检查接口是否允许返回

    import {LocaleMessage} from 'vue-i18n'
    export interface ILink {
        title: string | LocaleMessage;
        url?: string;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-21
      • 2019-02-23
      • 2017-05-02
      • 2018-11-23
      • 2018-03-11
      • 2018-01-21
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      相关资源
      最近更新 更多