- VisualStudio2022插件的安装及使用-编程手把手系列文章
- pprof-在现网场景怎么用
- C#实现的下拉多选框,下拉多选树,多级节点
- 【学习笔记】基础数据结构:猫树
在 Vue.js 3 中实现网页的国际化多语言,最常用的包是 vue-i18n,通常我们会与 vue-i18n-routing 一起使用.
vue-i18n 负责根据当前页面的语言渲染文本占位符,例如:
<span>{{ t('Login') }}</span>
当语言设置为中文时,会将 Login 渲染为“登录”.
vue-i18n-routing 负责将页面语言与 URL 绑定,例如:
https://githubstar.pro/zh-CN/repo
表示访问中文版的 /repo 路径.
将不同语言的网页放在不同的 URL 下有助于 SEO,因为可以在 <head> 部分添加语言信息,增加不同语言被搜索引擎索引的概率.
Google 对于多语言 Vue 站点的爬取机制如下:
第一步,安装一个 Vite 下使用 <i18n> 标签的插件:unplugin-vue-i18n.
然后调整 vite.config.js:
import { fileURLToPath, URL } from 'node:url';
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import VueDevTools from 'vite-plugin-vue-devtools';
import VueI18nPlugin from '@intlify/unplugin-vue-i18n/vite';
export default defineConfig({
plugins: [
vue(),
VueDevTools(),
VueI18nPlugin({}),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
});
添加插件后,我们可以在组件内使用 <i18n> 块:
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
const { t, locale } = useI18n({ inheritLocale: true, useScope: 'local' });
</script>
<template>
<span>{{ t('Login') }}</span>
</template>
<i18n lang="yaml">
en:
Login: 'Login to web'
zh-CN:
Login: '登录'
</i18n>
这里我们定义了两种不同的语言.
接下来,我们需要定义使用 URL 作为当前语言,编辑 router/index.ts:
import { createRouter as _createRouter, type RouteLocationNormalized } from 'vue-i18n-routing';
import { createWebHistory } from 'vue-router';
import HomeView from '@/views/HomeView.vue';
const locales = [
{
code: 'en',
iso: 'en-US',
name: 'English',
},
{
code: 'zh-CN',
iso: 'zh-CN',
name: '中文',
},
];
export function createRouter(i18n: any) {
const router = _createRouter(i18n, {
version: 4,
locales: locales,
defaultLocale: 'zh-CN',
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/home',
name: 'home',
component: HomeView,
},
],
});
return router;
}
我们定义了支持的语言种类,并将原来的 routes 包装起来,vue-i18n-routing 会自动生成所有支持语言的 routes:
/home
= 中文/en/home
= 英文由于我们设置了 defaultLocale: 'zh-CN',默认路径为中文.
然后,我们需要将源代码中涉及跳转的部分,例如:
router.push({ name: 'home' });
全部加上 localePath,表示是当前语言的 URL 路径下:
import { useLocalePath } from 'vue-i18n-routing';
const localePath = useLocalePath();
router.push(localePath({ name: 'home' }));
这样就完成了路径绑定.
有时,我们希望没有默认语言,而是根据用户的浏览器语言自动选择:
/zh-CN/home
= 中文/en/home
= 英文/home
-> 重定向 (浏览器偏好中文) -> /zh-CN/home
= 中文/home
-> 重定向 (浏览器偏好英文) -> /en/home
= 英文这时我们需要定义一个 store,这里使用 Pinia store,Vuex 同理.
import { usePreferredLanguages, useStorage } from '@vueuse/core';
import { defineStore } from 'pinia';
export const useLangStore = defineStore('lang', {
state: () => {
const savedLang = useStorage<string | null>('lang', null, undefined);
const systemLang = usePreferredLanguages();
return { savedLang, systemLang };
},
getters: {
lang: (state) => {
const lang = state.savedLang || state.systemLang[0];
if (lang.startsWith('zh')) {
return 'zh-CN';
} else {
return 'en';
}
},
},
actions: {
setLang(l?: string) {
if (!l) {
this.savedLang = null;
} else {
this.savedLang = l;
}
},
}
});
这段代码使用了 VueUse 中的 usePreferredLanguages 来获得用户偏好的浏览器语言,并用 useStorage 添加了一个 LocalStorage 中的存储项.
逻辑是:如果用户手动设定了语言(savedLang),则使用之;如果没有,则使用系统偏好的第一个语言。这样,我们只要取 lang 的值就可以得到最终的偏好语言是中文还是英文.
然后,我们需要定义一个路径守卫,以自动处理 URL 中没有语言的情况.
import { createRouter as _createRouter, type RouteLocationNormalized } from 'vue-i18n-routing';
import { createWebHistory } from 'vue-router';
import HomeView from '@/views/HomeView.vue';
const locales = [
{
code: 'en',
iso: 'en-US',
name: 'English',
},
{
code: 'zh-CN',
iso: 'zh-CN',
name: '中文',
},
{
code: '',
iso: '',
name: '',
}
];
export function createRouter(i18n: any) {
const router = _createRouter(i18n, {
version: 4,
locales: locales,
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/home',
name: 'home',
component: HomeView,
},
],
});
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized) => {
const lang = useLangStore();
const pathLocale = to.path.split('/')[1];
if ((!pathLocale) || (!locales.some(locale => locale.code === pathLocale))) {
return `/${lang.lang}${to.path}`;
}
});
return router;
}
这里需要注意三点:
locales
,这样请求才能到达 router.beforeEach
。defaultLocale
。useLangStore()
这行代码必须放在 router.beforeEach
中,而不能放在模块顶端,因为加载模块时 Pinia 还没有启动。这样,就实现了无语言路径自动跳转到当前偏好语言路径.
然后,可以在导航栏增加一个按钮,来手动切换语言,例如:
<script setup lang="ts">
import { useLocalePath, useSwitchLocalePath } from 'vue-i18n-routing';
import { useLangStore } from '@/stores/lang';
const lang = useLangStore();
const { t, locale } = useI18n({ inheritLocale: true, useScope: 'local' });
</script>
<template>
<div
@click="
lang.setLang('en');
router.push(switchLocalePath('en'));
menuShown = '';
"
class="py-2 px-2 gap-2 flex items-center cursor-pointer hover:bg-slate-400/10"
:class="{ 'text-sky-300': locale == 'en' }"
role="option"
tabindex="-1"
:aria-selected="locale == 'en'"
>
<IconEnglish class="w-5 h-5 text-slate-400 dark:text-slate-200" />
English
</div>
<div
@click="
lang.setLang('zh-CN');
router.push(switchLocalePath('zh-CN'));
menuShown = '';
"
class="py-2 px-2 gap-2 flex items-center cursor-pointer hover:bg-slate-400/10"
:class="{ 'text-sky-300': locale == 'zh-CN' }"
role="option"
tabindex="-1"
:aria-selected="locale == 'zh-CN'"
>
<IconChinese class="w-5 h-5 text-slate-400 dark:text-slate-200" />
中文
</div>
</template>
这里,我们在刚才定义的 store 中存储当前手动设定的语言,同时使用 switchLocalePath 来实现路径和语言的切换.
同一内容的不同语言版本应该在 head 中进行标注,并指向所有其他替代页面(参见 Google SEO)。这里我们可以在 App.vue 中用 useLocaleHead 和来自 @unhead/vue 包的 useHead 进行设置:
import { useLocaleHead } from 'vue-i18n-routing';
import { useHead } from '@unhead/vue';
const i18nHead = useLocaleHead({ addSeoAttributes: true, defaultLocale: null, strategy: null });
onMounted(() => {
useHead({
htmlAttrs: computed(() => ({
lang: i18nHead.value.htmlAttrs!.lang,
})),
link: computed(() => [...(i18nHead.value.link || [])]),
meta: computed(() => [...(i18nHead.value.meta || [])]),
});
});
这样就基本实现了一个多语言的国际化站点。可能在进行前端翻译的同时,后端也需要进行翻译,请期待下一期:Python Flask 后端如何接入 i18n 实现国际化多语言! 。
案例:GithubStar.Pro 的前端界面国际化多语言,是使用本文所述的方法实现的,各位可以看看效果.
也欢迎各位使用 GithubStar.Pro 互赞平台,提高您的开源项目知名度,收获更多用户.
最后此篇关于Vue3如何接入i18n实现国际化多语言的文章就讲到这里了,如果你想了解更多关于Vue3如何接入i18n实现国际化多语言的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
至少在某些 ML 系列语言中,您可以定义可以执行模式匹配的记录,例如http://learnyouahaskell.com/making-our-own-types-and-typeclasses -
这可能是其他人已经看到的一个问题,但我正在尝试寻找一种专为(或支持)并发编程而设计的语言,该语言可以在 .net 平台上运行。 我一直在 erlang 中进行辅助开发,以了解该语言,并且喜欢建立一个稳
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be
我正在寻找一种进程间通信工具,可以在相同或不同系统上运行的语言和/或环境之间使用。例如,它应该允许在 Java、C# 和/或 C++ 组件之间发送信号,并且还应该支持某种排队机制。唯一明显与环境和语言
我有一些以不同语言返回的文本。现在,客户端返回的文本格式为(en-us,又名美国英语): Stuff here to keep. -- Delete Here -- all of this below
问题:我希望在 R 中找到类似 findInterval 的函数,它为输入提供一个标量和一个表示区间起点的向量,并返回标量落入的区间的索引。例如在 R 中: findInterval(x = 2.6,
我是安卓新手。我正在尝试进行简单的登录 Activity ,但当我单击“登录”按钮时出现运行时错误。我认为我没有正确获取数据。我已经检查过,SQLite 中有一个与该 PK 相对应的数据。 日志猫。
大家好,感谢您帮助我。 我用 C# 制作了这个计算器,但遇到了一个问题。 当我添加像 5+5+5 这样的东西时,它给了我正确的结果,但是当我想减去两个以上的数字并且还想除或乘以两个以上的数字时,我没有
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 4 年前。 Improve th
这就是我所拥有的 #include #include void print(int a[], int size); void sort (int a[], int size); v
你好,我正在寻找我哪里做错了? #include #include int main(int argc, char *argv[]) { int account_on_the_ban
嘿,当我开始向数组输入数据时,我的代码崩溃了。该程序应该将数字读入数组,然后将新数字插入数组中,最后按升序排列所有内容。我不确定它出了什么问题。有人有建议吗? 这是我的代码 #include #in
我已经盯着这个问题好几个星期了,但我一无所获!它不起作用,我知道那么多,但我不知道为什么或出了什么问题。我确实知道开发人员针对我突出显示的行吐出了“错误:预期表达式”,但这实际上只是冰山一角。如果有人
我正在编写一个点对点聊天程序。在此程序中,客户端和服务器功能写入一个唯一的文件中。首先我想问一下我程序中的机制是否正确? I fork() two processes, one for client
基本上我需要找到一种方法来发现段落是否以句点 (.) 结束。 此时我已经可以计算给定文本的段落数,但我没有想出任何东西来检查它是否在句点内结束。 任何帮助都会帮助我,谢谢 char ch; FI
我的函数 save_words 接收 Armazena 和大小。 Armazena 是一个包含段落的动态数组,size 是数组的大小。在这个函数中,我想将单词放入其他称为单词的动态数组中。当我运行它时
我有一个结构 struct Human { char *name; struct location *location; int
我正在尝试缩进以下代码的字符串输出,但由于某种原因,我的变量不断从文件中提取,并且具有不同长度的噪声或空间(我不确定)。 这是我的代码: #include #include int main (v
我想让用户选择一个选项。所以我声明了一个名为 Choice 的变量,我希望它输入一个只能是 'M' 的 char 、'C'、'O' 或 'P'。 这是我的代码: char Choice; printf
我正在寻找一种解决方案,将定义和变量的值连接到数组中。我已经尝试过像这样使用 memcpy 但它不起作用: #define ADDRESS {0x00, 0x00, 0x00, 0x00, 0x0
我是一名优秀的程序员,十分优秀!