2017-10-06 398 views
0
  1. 我的主要app.js如何在vue-route中使用vue-i18n?

     import Vue from 'vue' 
         import language from './language' 
         import VueI18n from 'vue-i18n' 
    
         Vue.use(VueI18n) 
         const i18n = new VueI18n({ 
          locale: 'en', 
          messages: language.messages, 
         }) 
    
         import router from './router' 
         new Vue({ 
          el: '#app', 
          i18n, 
          router, 
          template: '<App/>', 
          components: { App } 
         }) 
    
  2. 的language.js

     export default { 
          messages : { 
          en: { 
           hello: 'hello!' 
           }, 
           ja: { 
           hello: 'こんにちは!' 
           }, 
           zh: { 
           hello: '你好!' 
           } 
          } 
         } 
    
  3. 我的問題是下面route.js代碼,這是我不能用this.$i18n.t('hello'),因爲$i18n是無法使用。

     import Vue from 'vue' 
         import Router from 'vue-router' 
    
         export const myRouteMap = [ 
    
          { 
          path: '/', 
          component: MyComponent, 
          redirect: '/myHome', 
          //name: 'Home', 
          name: this.$i18n.t('hello') // can't use $i18n here. 
          } 
         ] 
    

有沒有人也有類似情況,想在VUE路由使用國際化,並解決了問題?

+0

'this'是不是在文件中的Vue的實例。你爲什麼試圖將路由名稱綁定到一個翻譯的變量?該名稱不應該改變 – thanksd

+0

我正在使用'route.name'來向用戶界面顯示,並希望將其更改爲不同的語言。 – user2650480

回答

1

在您的例子this.i18n不會被定義,因爲它不是在該文件的背景下,Vue的實例。

你根本問題是,你正試圖把顯示數據在route的定義。這是一般的糟糕做法,並會導致像您遇到的問題。

routename屬性應該是路徑的唯一標識符,並且不應該被限定後更改。

如果您希望將Vue實例的屬性與已轉換的路由名稱相關聯(對於我的口味而言,它仍然過於緊密),您可以在爲路由指定的Vue組件中執行此操作。

computed: { 
    title() { 
    return this.$i18n.t(this.$route.name); 
    } 
} 

真的,不過,你不應該立足route對象上的顯示數據。好像這將是更清晰,更少的工作只是指定要傳遞給this.$i18n.t的定義爲相關的屬性翻譯消息鍵:

computed: { 
    title() { 
    return this.$i18n.t('hello'); 
    } 
} 
+0

謝謝,我現在明白了。我注意到Vue實例在該路由文件中不可用。在我看到您的消息之前,我將我的翻譯代碼移至導航組件。這是你所描述的。所以我給路由對象添加了另一個屬性名,所以'{path:'/',name ='こんにちは',text_code ='hello'}',所以我的導航代碼是'

{{$t(route_item.text_code)}}
'。 – user2650480