目 录CONTENT

文章目录

前端项目搭建笔记 Day2

Jinty
2024-07-30 / 0 评论 / 0 点赞 / 30 阅读 / 14594 字

项目国际化配置

安装vue-i18n依赖

# 可选
pnpm add vue-i18n

配置i18n

src/locates/zh-CN.json

{
  "selectColumns": "选择列",
  "export": "导出",
  "upload": "上传"
}

src/locates/en.json

{
  "selectColumns": "Select Columns",
  "export": "Export",
  "upload": "Upload"
}

src/config/i18n.config.ts

import { createI18n } from "vue-i18n";
import { primeVueLocalesMessages } from "./primevue.config";
import zhCN from "../locales/zh-CN.json";
import en from "../locales/en.json";
import appConfig from "../config/app.config";


// 创建VueI18n实例并配置
const i18n = createI18n({
  legacy: false, // 设置为 false,启用 composition API 模式
  locale: appConfig.defaultLocale(), // 设置默认语言
  fallbackLocale: appConfig.LOCALE_ZH_CN, // 设置后备语言
  messages: {
    primevue: primeVueLocalesMessages,
    "zh-CN": {
      ...zhCN,
    },
    en: {
      ...en,
    },
  }, // 设置翻译消息
});
export const setupI18n = (app: any) => {
  app.use(i18n);
};

export default i18n;

使用I18n

src/main.ts

import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import { setupPrimeVue } from "./config/primevue.config";
import { setupI18n } from "./config/i18n.config";

function loadApp() {
  const app = createApp(App);
  setupPrimeVue(app);
  setupI18n(app);
  app.mount("#app");
}

loadApp();

语言切换组件

LangSwitcher.vue

<script setup lang="ts" name="LangSwitcher">
// import { useLangStore } from "@/store/lang";
import { useI18n } from "vue-i18n";
import { usePrimeVue } from "primevue/config";
import { getLocaleMessages } from "../config/primevue.config";
// import { computed } from "vue";
import { ref } from "vue";
import { onMounted } from "vue";
// const store = useLangStore();
const { locale } = useI18n();
const primevue = usePrimeVue();

const switchLanguage = (event: any) => {
  const langOption = event.value;
  // if (store.language === value) return;
  locale.value = langOption.lang;
  // store.changeLang(value);
  primevue.config.locale = getLocaleMessages(langOption.lang);
};

const langOptions = [
  { lang: "zh-CN", name: "简体中文" },
  { lang: "en", name: "English" },
];
const selectedLang = ref(langOptions[locale.value === "zh-CN" ? 0 : 1]);
// const selectLang = computed(() => {
//   return langOptions[locale.value === "zh-CN" ? 0 : 1];
// });
onMounted(() => {
  // store.language = locale.value;
  primevue.config.locale = getLocaleMessages(locale.value);
});
</script>

<template>
  <div class="card flex justify-center">
    <Select
      v-model="selectedLang"
      :options="langOptions"
      optionLabel="name"
      placeholder=""
      checkmark
      :highlightOnSelect="false"
      class="w-full md:w-56"
      @change="switchLanguage"
    />
  </div>
</template>

<style scoped></style>

src/App.vue

<template>
  <LangSwitcher></LangSwitcher>
  <div class="card flex flex-col gap-6 items-center justify-center">
    <Toast />
    <FileUpload
      ref="fileupload"
      mode="basic"
      name="demo[]"
      url="/api/upload"
      accept="image/*"
      :maxFileSize="1000000"
      @upload="onUpload"
    />
    <Button
      :label="i18nText.upload.value"
      @click="upload"
      severity="secondary"
    />
  </div>
  <div>
    <DataTable :value="products" tableStyle="min-width: 50rem">
      <template #header>
        <div style="text-align: left">
          <MultiSelect
            :modelValue="selectedColumns"
            :options="columns"
            optionLabel="header"
            @update:modelValue="onToggle"
            display="chip"
            :placeholder="i18nText.selectColumns.value"
          />
        </div>
      </template>
      <Column field="id" header="ID" />
      <Column
        v-for="(col, index) of selectedColumns"
        :field="col.field"
        :header="col.header"
        :key="col.field + '_' + index"
      ></Column>
    </DataTable>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import LangSwitcher from "./components/LangSwitcher.vue";
import useI18nText from "./hooks/i18nText";
import testData from "./data/test";
const i18nText = useI18nText();
onMounted(() => {});

const columns = ref([
  { field: "name", header: "姓名" },
  { field: "company", header: "公司" },
]);
const selectedColumns = ref(columns.value);
const products = ref(testData.data);
const onToggle = (val: string[]) => {
  selectedColumns.value = columns.value.filter((col: any) => val.includes(col));
};
const fileupload = ref();

const upload = () => {
  fileupload.value.upload();
};

const onUpload = () => {
  console.log("onUpload");
};
</script>

使用效果

状态管理Pinia

安装pinia依赖

pnpm add pinia

配置pinia

src/config/pinia.config.ts

import { createPinia } from "pinia"; // import pinia

const pinia = createPinia(); // create pinia instance

export const setupPiniaStore = (app: any) => {
  app.use(pinia);
};

// export pinia instance
export default pinia;

使用pinia对本地语言进行状态管理

src/main.ts

import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import { setupPrimeVue } from "./config/primevue.config";
import { setupI18n } from "./config/i18n.config";
import { setupPiniaStore } from "./config/pinia.config";
function loadApp() {
  const app = createApp(App);
  setupPrimeVue(app);
  setupI18n(app);
  setupPiniaStore(app);
  app.mount("#app");
}

loadApp();

src/config/stores/lang.ts

import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { useI18n } from "vue-i18n";
import { usePrimeVue } from "primevue/config";
import { getLocaleMessages } from "../primevue.config";
import appConfig from "../app.config";
export const useLangStore = defineStore("lang", () => {
  const i18n = useI18n();
  const primeVue = usePrimeVue();

  const langOptions = appConfig.langOptions;
  const lang = ref(appConfig.defaultLocale());

  const setLang = (newLang: string) => {
    if (lang.value === newLang) return;
    lang.value = newLang;
    i18n.locale.value = newLang;
    primeVue.config.locale = getLocaleMessages(newLang);
    sessionStorage.setItem(appConfig.LANG_SESSION_KEY, newLang);
  };

  const selectedLocale = computed(() => {
    return (
      langOptions.find((option) => option.lang === lang.value) || langOptions[0]
    );
  });

  return {
    langOptions,
    lang,
    selectedLocale,
    setLang,
  };
});

src/components/LangSwitcher.vue

<script setup lang="ts" name="LangSwitcher">
import { useLangStore } from "../config/stores/lang";
import { ref } from "vue";

const langStore = useLangStore();
const switchLanguage = (event: any) => {
  const langOption = event.value;
  langStore.setLang(langOption.lang);
};
const selectedLang = ref(langStore.selectedLocale);
</script>

<template>
  <div class="card flex justify-center">
    <Select
      v-model="selectedLang"
      :options="langStore.langOptions"
      optionLabel="name"
      placeholder=""
      checkmark
      :highlightOnSelect="false"
      class="w-full md:w-56"
      @change="switchLanguage"
    />
  </div>
</template>

<style scoped></style>

测试结果

Tailwind Css样式库

安装tailwindcss相关依赖

pnpm install -D tailwindcss postcss autoprefixer

# 初始化配置文件
npx tailwindcss init -p
# 将在项目根路径下生成tailwind.config.js、postcss.config.js文件

定制配置

tailwind.config.ts

/** @type {import('tailwindcss').Config} */
// See https://tailwindcss.com/docs/configuration for details
export default {
  content: ["./index.html", "./src/**/*.{vue,js,ts,jsx,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};

将Tailwind指令添加到项目css中

src/style.css

@tailwind base;
@tailwind components;
@tailwind utilities;

添加代码测试

  <h1 className="text-3xl font-bold underline">Hello world!</h1>
  <p class="text-blue-600 text-2xl text-center">
    This is a Vue 3 + Vite + Typescript + Tailwind project.
  </p>

tailwindcss-primeui集成

预设资源

primevue-tailwind-presets-4.0.0.rc.1.zip

将presets放在src路径下

配置primevue

src/config/promevue.config.ts

import PrimeVue from "primevue/config";
// 使用Aura主题
// import Aura from "@primevue/themes/aura";
// https://github.com/primefaces/primevue-tailwind/releases
import Aura from "../presets/aura"; //import preset
import Lara from "../presets/lara"; //import preset
// PrimeVue本身仅支持英语,这里我们使用PrimeVue社区语言来进行国际化配置
import zhCN from "primelocale/zh-CN.json";
import en from "primelocale/en.json";

import appConfig from "./app.config";

// 获取当前语言,默认中文
const defaultLocale = appConfig.defaultLocale();

// 定义PrimeVue支持的语言包
export const primeVueLocalesMessages: any = {
  ...zhCN, // 简体中文
  ...en, // 英文
  // "zh-CN": zhCN["zh-CN"], // 简体中文
  // en: en["en"], // 英文
};

// 获取语言包
export const getLocaleMessages = (locale: string): any => {
  return (
    primeVueLocalesMessages[locale] || primeVueLocalesMessages[defaultLocale]
  );
};

// 定义PrimeVue预设配置
export const primeVuePresetConfig = {
  // // 主题
  // theme: {
  //   preset: Aura,
  // },
  unstyled: true, // 无样式
  pt: Aura, // 主题
  // 语言消息
  locale: getLocaleMessages(defaultLocale),
};

// 注册PrimeVue方法
export const setupPrimeVue = (app: any) => {
  app.use(PrimeVue, primeVuePresetConfig);
};

安装tailwindcss-primeui插件

pnpm add tailwindcss-primeui

配置tailwindcss

tailwindcss.config.ts

/** @type {import('tailwindcss').Config} */
// See https://tailwindcss.com/docs/configuration for details
export default {
  content: [
    "./index.html",
    "./presets/**/*.{js,vue,ts}",
    "./src/**/*.{vue,js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [require("tailwindcss-primeui")],
};

edge测试结果

note:低版本chrome存在兼容性问题

参考资料

0

评论区