Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.
In this article, we’ll look at how to create multilingual Vue apps with vue-i18n.
To get started, we install the package by writing:
npm i vue-i18n
Then we can write:
main.js
import Vue from "vue";
import App from "./App.vue";
import VueI18n from "vue-i18n";
Vue.use(VueI18n);
const messages = {
en: {
message: {
hello: "hello"
}
},
fr: {
message: {
hello: "bonjour"
}
}
};
const i18n = new VueI18n({
locale: "fr",
messages
});
Vue.config.productionTip = false;
new Vue({
i18n,
render: h => h(App)
}).$mount("#app");
And we can display the translation by writing:
<template>
<div id="app">
<p>{{ $t("message.hello") }}</p>
</div>
</template>
<script>
export default {
name: "App"
};
</script>
We can interpolate expression in our messages by writing:
import Vue from "vue";
import App from "./App.vue";
import VueI18n from "vue-i18n";
Vue.use(VueI18n);
const messages = {
en: {
message: {
hello: "{msg} world"
}
},
fr: {
message: {
hello: "bonjour"
}
}
};
const i18n = new VueI18n({
locale: "en",
messages
});
Vue.config.productionTip = false;
new Vue({
i18n,
render: h => h(App)
}).$mount("#app");
And in our component, we can write:
<template>
<div id="app">
<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>
</div>
</template>
<script>
export default {
name: "App"
};
</script>
Then we get hello world
displayed on screen.
#programming #javascript #web-development #vuejs