[英]How to set reactive locale in all Vue3 Components?
我有以下项目结构( index.vue
):
<template>
<div class="container">
<navbar></navbar>
<social-media-bar></social-media-bar>
<main>
<home></home>
<news></news>
<vision></vision>
<event-section></event-section>
<artwork></artwork>
<about></about>
<donate></donate>
<contact></contact>
<partners></partners>
</main>
<footer-component></footer-component>
</div>
</template>
我想从navbar.vue
内部更改app-language
:
<template>
<div class="nav-bar">
<fa class="icon-locale" @click="toggleLocale" :icon="[ 'fa', 'language' ]" size="2x"></fa>
<div class="locale-menu" :class="{ locale__open: isActiveLocale }">
<p @click="toggleLocale(); setLocale('en');">en</p>
<p @click="toggleLocale(); setLocale('de');">de</p>
<p @click="toggleLocale(); setLocale('ar');">ar</p>
</div>
</div>
</template>
<script setup>
import {ref} from "vue";
import {createI18n} from 'vue-i18n';
const isActiveLocale = ref(false);
const toggleLocale = () => {
isActiveLocale.value = !isActiveLocale.value;
}
const i18n = createI18n({});
const setLocale = (locale) => {
i18n.global.locale = locale
};
</script>
基本上这会打开一个带有en, de, ar
语言环境的locale menu
,它启动一个@click
事件,相应地更改i18n.global.locale
。
我需要在home
组件中设置新设置的i18n.global.locale
。
home.vue
:
<template>
<section id="home" class="home">
<h2>{{ state.heading[state.locale] }}</h2>
</section>
</template>
<script setup>
import {reactive} from 'vue';
import {useI18n} from 'vue-i18n';
const {locale} = useI18n()
const loc = locale.value.substring(0, 2)
const state = reactive({
locale: loc
})
</script>
我想是让新设置的i18n.global.locale
从navbar.vue
到state.locale
在home.vue
被动。 由于navbar
和home
没有parent/child
,我是否必须为此构建一个EventBus
或者是否有更优雅的解决方案,也许使用i18n
库?
编辑:
这是函数,它应该全局更改locale
,但它只将它设置在i18n
内,看起来唯一可能的反应是i18n
的messages
,我没有使用。
const setLocale = () => {
i18n.global.locale = 'de'
console.log(i18n.global.locale);
};
我需要全局更改语言环境字符串,以便我可以在所有组件中反应性地使用它。
i18n.js
import { createI18n } from "vue-i18n";
export const i18n = createI18n({
locale: "en",
messages: {
en: {
message: {
language: "Language",
hello: "hello world!"
}
},
ja: {
message: {
language: "言語",
hello: "こんにちは、世界!"
}
}
}
});
主文件
import { createApp } from "vue";
import App from "./App.vue";
import { i18n } from "./i18n";
createApp(App).use(i18n).mount("#app");
应用程序
<template>
<button @click="switch">switch to ja</button>
<p>{{ $t("message.hello") }}</p>
</template>
<script>
export default {
name: "App",
methods: {
switch() {
// $i18n is reactively
this.$i18n.locale = "ja";
},
},
};
</script>
我找到了一种使用sessionStorage
在vue
组件之间传递变量的超级简单方法。 只需定义:
sessionStorage.whatever = 'whateverYouWant'
您可以在所有组件中使用sessionStorage.whatever
。 除了localStorage
, sessionStorage
将在浏览器/选项卡关闭时重置。 我用它来传递选定的locale
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.