本文将记录如何实现多语言切换

安装依赖

npm i vue-i18n pinia

新建 src/locale/zh-cn.ts

// src/locale/zh-cn.ts
export default {
    searchInput: {
        placeholdar: '请输入',
    },
};

新建 src/locale/en.ts

// src/locale/en.ts
export default {
    searchInput: {
        placeholdar: 'Please enter',
    },
};

新建 src/locale/index.ts

// src/locale/index.ts
import { zhCn, en } from 'element-plus/es/locale/index.mjs';
import zhCnLocal from './zh-cn';
import enLocal from './en';

export default {
    zhCn: Object.assign(zhCn, zhCnLocal),
    en: Object.assign(en, enLocal),
};

新建 src/store/user.ts

// src/store/user.ts
import { defineStore } from 'pinia';
import locale from '@/locale';

export default defineStore('useUserStore', {
    state() {
        return {
            lang: 'zhCn',
        };
    },
    getters: {
        locale(): any {
            return locale[this.lang as 'zhCn'];
        },
    },
    actions: {
        changeLang(lang: string) {
            this.lang = lang;
        },
    },
});

修改 src/main.ts

// src/main.ts
import { createApp } from 'vue';
import App from './App.vue';
import '@/style/index.scss';
import { getRouterList } from '@/router/config';
import { initRouter } from '@/router/index';
import { createPinia } from 'pinia'; // 新增

(async () => {
    const routerList = await getRouterList();

    const router = initRouter(routerList as any[]);
    const app = createApp(App);
    app.use(router);
    app.use(createPinia()); // 新增
    app.mount('#app');
})();

修改src/App.vue

<template>
    <ElConfigProvider :locale="userStore.locale">
        <router-view></router-view>
    </ElConfigProvider>
</template>
<script setup lang="ts">
// import { zhCn } from 'element-plus/es/locale/index.mjs';
import useUserStore from '@/store/user';

const userStore = useUserStore();
</script>

修改 src/home.vue

<template>
    <el-select v-model="userStore.lang">
        <el-option
            label="中文"
            value="zhCn"
        >
        </el-option>
        <el-option
            label="英文"
            value="en"
        ></el-option>
    </el-select>

    <el-input :placeholder="t('searchInput.placeholdar')"></el-input>
</template>

<script setup lang="ts">
import useUserStore from '@/store/user';
import { useLocale } from 'element-plus';

const userStore = useUserStore();
const { t } = useLocale();
</script>

似曾相识
169 声望8 粉丝