Localization with Framework7 and Vue

by Jeffrey van Rossum

While creating an app with Framework7, I wanted to be able to localize strings to support other languages. I found the Vue I18n package, and it is actually quite easy to apply to a Framework7 Vue project.

Below you’ll find the steps to achieve this. I’m assuming you’ve already created a Vue Framework7 app. If you haven’t, you can follow the installationinstructions.

Install Vue I18n

From the terminal (from your app folder), run the following command to install vue-i18n.

npm install vue-i18n

Modify your app.js

Next, in src/js/app.js, make sure to import vue-i8n like this, just after the vue-import.

import VueI18n from 'vue-i18n';

Then directly after that, you add this:

Vue.use(VueI18n);

Next, we need to create an instance of VueI18n. We give this instances the translations and the current locale. First, let’s make a quick object that contains our translations.

const messages = {
  en: {
    message: {
      hello: 'Mark Knopfler is awesome'
    }
  },
  nl: {
    message: {
      hello: 'Mark Knopfler is te gek!'
    }
  }
};
Now let’s create the VueI18n instance:

const i18n = new VueI18n({
  locale: 'nl', // set locale
  messages, // set locale messages
});

At the bottom of your app.js, you’ll find the main Vue instance of your app. We need to add i18n to this instance, like this:

new Vue({
    el: '#app',
    render: (h) => h(App),
    components: {
        app: App
    },
    i18n
});

Using the translations in your components

Now, within your components (our pages — that are components), you can retrieve your translations like this:

{{ $t("message.hello") }}

Separate file for translations

As you’re messages object gets bigger, you might want to put them in a separate file. You could do this by, for example, creating a messages.js file in your js-folder. That file would look something like this:

const messages = {
  en: {
    message: {
      hello: 'Mark Knopfler is awesome'
    }
  },
  nl: {
    message: {
      hello: 'Mark Knopfler is te gek!'
    }
  }
};

export { messages };

Then, within your app.js, you can import the messages like this (before the Vuei18n instance):

import { messages } from './messages.js'

I hope this helps anyone!

This post was last modified 12 May 2020
Did you like this post?

If you sign up for my newsletter, I can keep you up to date on more posts like this when they are published.