Skip to content

路由国际化

流程

  • 新建 utils/i18n.js
js
/**
 * @Author: jsopy
 * @Date: 2025-01-18 20:32:37
 * @LastEditTime: 2025-01-18 20:32:43
 * @FilePath: /adminvue/src/utils/i18n.js
 * @Description:
 * @
 */
import { watch } from "vue";

import i18nAll from "@/i18n";

import { useI18n } from "vue-i18n";

export function generateTitle(title) {
  return i18nAll.global.t("message.route." + title);
}

/**
 *
 * @param  {...any} cbs 所有的回调
 */
export function watchSwitchLang(...cbs) {
  // 切换语言的方法
  const i18n = useI18n();
  watch(
    () => i18n.locale.value,
    () => {
      cbs.forEach((cb) => cb(i18n.locale.value));
    }
  );
}

使用

(1) 修改 SideBarItem.vue

vue
<template>
  <!-- 支持渲染多级 menu 菜单 -->
  <el-sub-menu v-if="route.children.length > 0" :index="route.path">
    <template #title>
      <SvgIcon :icon="route.meta.icon" size="16"></SvgIcon>
      <span class="title ml">{{ generateTitle(route.meta.title) }}</span>
    </template>
    <!-- 循环渲染 -->
    <el-menu-item
      v-for="(item, index) in route.children"
      :key="item.path"
      :index="item.path"
    >
      <template #title>
        <SvgIcon :icon="item.meta.icon" size="16"></SvgIcon>
        <span class="title ml">{{ generateTitle(item.meta.title) }}</span>
      </template>
    </el-menu-item>
  </el-sub-menu>
  <!-- 渲染 item 项 -->
  <el-menu-item v-else :index="route.path">
    <SvgIcon :icon="route.meta.icon" size="16"></SvgIcon>
    <template #title>
      <span :class="[useCollapse().sidebarOpened ? 'title' : 'title  ml']">{{
        generateTitle(route.meta.title)
      }}</span>
    </template>
  </el-menu-item>
</template>

<script setup>
import { useCollapse } from "@/stores/sidebaropen";
import { generateTitle } from "@/utils/i18n";
// 定义 props
defineProps({
  route: {
    type: Object,
    required: true,
  },
});
</script>

<style lang="scss">
.ml {
  margin-left: 10px;
}
</style>