[Vuejs]-Vue-treeselect component with Vue I18n

0👍

Initialize the i18n config as follows :

const messages = {
  en: {
    options: []
  },
  es: {
    options: []
  }
}

const i18n = new VueI18n({
  locale: 'en',
  messages,
})

Then in the mounted hook add the options via ajax call by looping through the available languages :

 ['en', 'es'].forEach(lng => {
      $.getJSON("https://raw.githubusercontent.com/javierpose/pruebas/master/my-" + lng + ".json", function(json) {
        vm.options = json;
        i18n.setLocaleMessage(lng, {
          options: json
        })

      });
    });

finally bind the select options prop $t('options').

The following example illustrates your case using radio buttons to change languages :

const messages = {
  en: {
    options: []
  },
  es: {
    options: []
  }
}

const i18n = new VueI18n({
  locale: 'en',
  messages,
})

Vue.component('treeselect', VueTreeselect.Treeselect)
var tree = new Vue({
  i18n,
  data: {
    value: null,
    clearOnSelect: true,
    closeOnSelect: true,
    selectAll: true,
    options: [],
    lang: 'en'
  },
  methods: {
    normalizer: function(node) {
      return {
        id: node.id,
        label: node.label,
        children: node.children,
      };
    },
  },
  mounted() {
    let vm = this;
    ['en', 'es'].forEach(lng => {
      $.getJSON("https://raw.githubusercontent.com/javierpose/pruebas/master/my-" + lng + ".json", function(json) {
        vm.options = json;
        i18n.setLocaleMessage(lng, {
          options: json
        })

      });
    });
  }
}).$mount('#app')
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.umd.min.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@riophae/vue-treeselect@^0.4.0/dist/vue-treeselect.min.css">
  <script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
</head>

<body>
  <div id="app">
    <input type="radio" id="en" value="en" v-model="$i18n.locale">
    <label for="en">English</label>
    <br>
    <input type="radio" id="es" value="es" v-model="$i18n.locale">
    <label for="es">Spanish</label>
    <br>
    <span>Language : {{ lang }}</span>


    <treeselect v-model="value" :multiple="true" :options="$t('options')" :clear-on-select="clearOnSelect" placeholder="placeholder english" noResultsText="Retry?">
      <label slot="option-label" slot-scope="{ node, shouldShowCount, count, labelClassName, countClassName }" :class="labelClassName">
                {{ node.label }}
            </label>
    </treeselect>
  </div>
</body>

Leave a comment