Skip to content

Commit

Permalink
根据url中的语言前缀,处理站点显示的翻译语言
Browse files Browse the repository at this point in the history
  • Loading branch information
tangly1024 committed Nov 8, 2024
1 parent 44d6756 commit 4d7b0f5
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 29 deletions.
24 changes: 1 addition & 23 deletions lib/global.js
Original file line number Diff line number Diff line change
Expand Up @@ -89,29 +89,7 @@ export function GlobalContextProvider(props) {

// 添加路由变化时的语言处理
useEffect(() => {
const handleRouteChange = (url) => {
// 从路径中提取语言前缀
const pathSegments = url.split('/')
const pathLang = pathSegments[1]

// 检查是否是有效的语言路径
if (pathLang === 'en' || pathLang === 'zh') {
const targetLang = pathLang === 'en' ? 'en-US' : 'zh-CN'

// 直接更新语言,不使用 localStorage
updateLang(targetLang)
updateLocale(generateLocaleDict(targetLang))
}
}

// 初始化时处理当前路径
handleRouteChange(router.asPath)

// 监听路由变化
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
initLocale(router.locale, changeLang, updateLocale)
}, [router])

useEffect(() => {
Expand Down
18 changes: 12 additions & 6 deletions lib/lang.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,21 +65,27 @@ export function generateLocaleDict(langString) {
}

/**
* 初始化站点翻译
* 根据用户当前浏览器语言进行切换
* 站点翻译
* 借助router中的locale机制,根据locale自动切换对应的语言
*/
export function initLocale(lang, locale, changeLang, changeLocale) {
export function initLocale(locale, changeLang, updateLocale) {
if (isBrowser) {
// 只使用 URL 参数,忽略 localStorage
const queryLang = getQueryVariable('locale') || getQueryVariable('lang')
// 根据router中的locale对象判断当前语言:表现为前缀中包含 zh、en 等。
let pathLocaleLang = null
if (locale === 'en' || locale === 'zh') {
pathLocaleLang = locale === 'en' ? 'en-US' : 'zh-CN'
}
// 如果有query参数切换语言则优先
const queryLang =
getQueryVariable('locale') || getQueryVariable('lang') || pathLocaleLang

if (queryLang) {
const match = queryLang.match(/[a-zA-Z]{2}(?:-[a-zA-Z]{2})?/)
if (match) {
const targetLang = match[0]
changeLang(targetLang)
const targetLocale = generateLocaleDict(targetLang)
changeLocale(targetLocale)
updateLocale(targetLocale)
}
}
}
Expand Down

0 comments on commit 4d7b0f5

Please sign in to comment.