JSFiddle - React, Tailwind, and code Playground

by André Kuhlmann

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
  <ul>
      <li><a href="#" v-on="click: setLocale('en')">en</a>
      </li>
      <li><a href="#" v-on="click: setLocale('de')">de</a>
      </li>
      <li><a href="#" v-on="click: setLocale('fr')">fr</a>
      </li>
  </ul>{{ t('root test') }}
  <child1></child1>
  <child2></child2>
</div>

JavaScript

Vue.config.debug = true;

var i18n = {
    data: {
        translator: {
            locale: null
        }
    },
    methods: {
        $setLocale: function (locale) {
            this.translator.locale = locale
        },
        $t: function (string, variables) {
            if (!this.translator.locale) {
                return 'untranslated: ' + string;
            }
            return this.translator.locale + ': ' + string;
        },
        setLocale: function (locale) {
            this.$root.$setLocale(locale);
        },
        t: function (string, variables) {
            return this.$root.$t(string, variables);
        }
    }
};

new Vue({
    mixins: [i18n],
    el: '#app',
    data: {},
    methods: {},
    components: {
        child1: {
            mixins: [i18n],
            template: "<div>{{ t('test1') }}</div>",
            data: function() {},
            methods: {},
            ready: function() {
                console.log("child1 is own root after ready?", this === this.$root);
                console.log(this.$root);
            }
        },
        child2: {
            mixins: [i18n],
            template: "<div>{{ t('test2') }}</div>",
            data: function() {},
            methods: {}
        }
    }
});