Internationalization Plugin for Vue.js
Showcase the implementation of a lightweight internationalization plugin to switch languages and manage translation strings.
Vue.use(VueI18n);
const messages = {
en: {
message: {
hello: 'hello world'
}
},
es: {
message: {
hello: 'hola mundo'
}
}
};
const i18n = new VueI18n({
locale: 'en', // set locale
messages, // set locale messages
});
new Vue({ i18n }).$mount('#app');
This initializes the VueI18n plugin, defines messages for 'en' and 'es' locales, sets the default locale, and mounts the Vue app with the internationalization plugin.
<div id="app">
<p>{{ $t('message.hello') }}</p>
<button @click="changeLocale('en')">English</button>
<button @click="changeLocale('es')">Español</button>
</div>
This is the HTML that displays a translated text and buttons to switch between English and Spanish.
methods: {
changeLocale(lang) {
this.$i18n.locale = lang;
}
}
Vue instance method to change the language.
body {
font-family: 'Arial', sans-serif;
}
button {
margin: 5px;
padding: 10px;
}
Basic CSS for styling the body font and button spacing and padding.