avatar
fireworks99
keep hungry keep foolish

Vue i18n

Vue 国际化

  1. $t
  2. vue-i18n
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
    <div id="app">
        <h1>{{ $t('welcome-message') }}</h1>
        <button @click="changeLang('en')">English</button>
        <button @click="changeLang('zh')">中文</button>
        <button @click="changeLang('nl')">Dutch</button>
    </div>

    <script>
        const i18nPlugin = {
            // Implement this!
            install(Vue, locales) {
                Vue.prototype.$t = function(id) {
                    return locales[this.$root.lang][id]
                }
            }
        }

        Vue.use(i18nPlugin, /* option */ {
            en: { 'welcome-message': 'hello' },
            zh: { 'welcome-message': '你好' },
            nl: { 'welcome-message': 'Hallo' }
        })

        new Vue({
            el: '#app',
            data: {
                lang: 'en'
            },
            methods: {
                changeLang(lang) {
                    this.lang = lang
                }
            }
        })
    </script>
</body>

</html>

切换语言的关键:插件与响应性的结合。

$t方法在模板(Template)中被调用,那么当Template => Render后,系统执行渲染函数时就会调用$t方法,而调用$t方法会调用lang的getter,触发Dep.depend(),新增依赖关系,那么在lang被更新时视图也会被更新。

Site by Baole Zhao | Powered by Hexo | theme PreciousJoy