【问题标题】:Vue-i18n not translating inside component script tagsVue-i18n 不翻译内部组件脚本标签
【发布时间】:2021-05-27 23:31:10
【问题描述】:

构建一个语言切换器,一切正常,但是当我在数据对象中使用 $t() 时,当我在语言之间切换时它不会是动态的。

Component.vue

<template>
   // loop menu here
  <div v-for="item in menu">
     {{ item.label }}
   </div>
</template>

<script>

const mainMenu = [
{
    label: $t('dashboard'),
},
{
    label: $t('users'),
},
{
    label: $t('settings'),
},
}
export default {
    data () {
        return {
           menu = MainMenu
        }
    }
}
</script>

i18n.js

// https://vue-i18n.intlify.dev/

import { createI18n } from 'vue-i18n'

export function loadLocalMessages () {
    const locales = require.context('../locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
    const messages = {}
    locales.keys().forEach(key => {
        const matched = key.match(/([A-Za-z0-9-_]+)\./i)
        if (matched && matched.length > 1) {
            const locale = matched[1]
            messages[locale] = locales(key)
        }
    })
    return messages;
}

const i18n = createI18n({
    locale: 'en',// .env not working
    fallbackLocale: 'en',// .env not working
    messages: loadLocalMessages(),
});
  
export default i18n

【问题讨论】:

    标签: vue.js vue-i18n


    【解决方案1】:

    data 在创建组件时只被调用一次,并且它不是响应式的。

    要使$t() 上的属性反应,它应该是computed

    export default {
      computed: {
        hello() {
          return this.$t('hello')
        }
      }
    }
    

    demo

    【讨论】:

    • 只需将menu[]data() 移动到computed,然后在模板中循环menu
    【解决方案2】:
    <template>
      <div v-for="item in menu">
         {{ item.label }}
       </div>
    </template>
    
    <script>
    
    export default {
      computed: {
        menu() {
          return [{
             label: this.$t('dashboard'),
           }, {
             label: this.$t('users'),
           }, {
             label: this.$t('settings'),
           }]
        }
      }
    }
    </script>
    
    

    【讨论】:

      猜你喜欢
      • 2019-10-14
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-14
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多