I'm working on a Vue.js app using Pinia for state management. I have a multilingual application with three languages (EN, RU, TJ), and I want to implement language switching using query parameters.
Here's a simplified version of my code:
this my main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { createI18n } from 'vue-i18n';
import { createPinia } from 'pinia';
import { productsStore } from './stores/products';
import EN from '../src/locale/en.json';
import RU from '../src/locale/ru.json';
import TJ from '../src/locale/tj.json';
const pinia = createPinia();
const app = createApp(App);
app.use(router);
app.use(pinia);
const store = productsStore();
const i18n = createI18n({
legacy: false,
locale: store.locale,
messages: {
EN: EN,
RU: RU,
TJ: TJ
}
});
app.use(i18n);
app.mount('#app');
this is store.js
import { defineStore } from "pinia";
export const productsStore = defineStore('products', {
state: () => ({
locale: 'TJ',
}),
})
router.js
import {
createRouter,
// createWebHashHistory
createWebHistory
} from "vue-router";
import Birthday from '../views/Birthday.vue'
import Gifts from '../views/Gifts.vue'
import Discounts from '../views/Discounts.vue'
import Mbback from '../views/Mb_back.vue'
const routes = [{
path: '/',
name: 'birthday',
component: Birthday
},
{
path: '/gifts',
name: 'gifts',
component: Gifts
},
{
path: '/discounts',
name: 'discounts',
component: Discounts
},
{
path: '/mb_back',
name: 'mb_back',
component: Mbback,
},
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
I have tried to set the locale in my Pinia store based on the query parameter, but it doesn't seem to work as expected. I've also set up my routes, and I want the language to change when the user provides a lang
query parameter in the URL.
What am I missing or doing wrong in my implementation? Any suggestions on how to properly implement language switching in a Vue.js app using Pinia and query parameters?
const language = ref(route.query?.lang); // initialize variable with change tracking capabilities from home?lang=en
watchEffect(() => {
language.value = route.query?.lang // update whenever the lang=en on address changes
if (language.value === 'en') {
}
else if (language.value === 'fr') {
}
}