I18n.vue 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <template>
  2. <main class="app-main">
  3. <router-tab
  4. :i18n="i18n"
  5. :tabs="tabs"
  6. />
  7. </main>
  8. </template>
  9. <script>
  10. import Vue from 'vue'
  11. export default {
  12. name: 'LangCustom',
  13. data () {
  14. return {
  15. currentLang: 'en',
  16. langs: {
  17. en: {
  18. i18n: 'I18n Page',
  19. page: 'Page {0}'
  20. },
  21. 'zh-CN': {
  22. i18n: '国际化页面',
  23. page: '页面 {0}'
  24. }
  25. },
  26. tabs: [
  27. '/i18n/lang',
  28. { to: '/i18n/page/1', title: ['page', 1] },
  29. { to: '/i18n/page/2', title: ['page', 2] }
  30. ]
  31. }
  32. },
  33. computed: {
  34. lang () {
  35. return this.langs[this.currentLang] || this.langs.en
  36. }
  37. },
  38. beforeCreate () {
  39. // 全局语言方法
  40. Vue.prototype.$lang = {
  41. set: lang => {
  42. this.currentLang = lang
  43. },
  44. get: () => this.currentLang,
  45. list: () => Object.keys(this.langs)
  46. }
  47. },
  48. methods: {
  49. i18n (key, params) {
  50. let lang = this.lang[key]
  51. return lang
  52. ? lang.replace(/(\{(\d+)\})/g, (match, $0, $1) => params[$1] || '') // 替换国际化中的列表参数
  53. : key
  54. }
  55. }
  56. }
  57. </script>