zhaobinglong / myBlog

https://zhaobinglong.github.io/myBlog/
MIT License
7 stars 0 forks source link

vue之国际化i18n #67

Open zhaobinglong opened 4 years ago

zhaobinglong commented 4 years ago

引入多语言插件

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

插件通常会为 Vue 添加全局功能。插件的范围没有限制——一般有下面几种:添加全局方法或者属性;添加全局资源:指令/过滤器/过渡等;通过全局 mixin 方法添加一些组件选项;添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。

准备多语言文本

<div id="app">
  <p>{{ $t("message.hello") }}</p>
</div>

const messages = {
  en: {
    message: {
      hello: 'hello world'
    }
  },
  ja: {
    message: {
      hello: 'こんにちは、世界'
    }
  }
}

// 注意,VueI18n在实例化的时候,多语言的文本就已经传递进去了
const i18n = new VueI18n({
  locale: 'ja', // 设置当前的语言
  messages, // 准备多语言的文本
})

使用

在vue根结点导入i18n

new Vue({
  i18n,
  router,
  store,
  render: h => h(App),
}).$mount('#app')

参考

https://segmentfault.com/a/1190000015008808