vue-i18n国际化在data中切换不起作用
(vue3+vite+pinia+i18n)
原因(why):data是一次性生产,只能在 data 初始化的时候拿到这些被国际化的值,并不能响应变化
官方解决办法:写在computed里面(但是我不想写在computed里面怎么办)
附上官方文档:i18n
解决方法一(最笨的方法):改变语言重刷页面,可以解决所有改变语言不更新问题
<script setup>
import { userStore } from "@/store/modules/user";
import i18n from "@/lang/i18n";
const user = userStore();
const changeLang = (item) => {
user.setLang(item.value);
window.location.reload();
};
<script>
ps:Vuex中
const local = i18n.global.locale;
state: () => ({
lang: local,
}),
actions:{
setLang(data) {
this.lang = data;
}
}
解决方法二(巧妙运用拼接,非常nice)
模板中:
<ul class="intruduce-top__des">
<li v-for="index in 3" :key="index">
{{ $t("home.f" + (index + 3)) }}
</li>
</ul>
解决方法三(通过监听locale重新赋值,可初始化你想写的所有,完美!!!)
模板中
<ul class="intruduce-top__des">
<li v-for="(item, index) in desWord" :key="index">
{{ item }}
</li>
</ul>
js
<script setup>
import { ref, watch } from "vue";
const locale = ref(i18n.global.locale);
const _this = i18n.global;
const desWord = ref([
_this.t("home.f4"),
_this.t("home.f5"),
_this.t("home.f6"),
]);
watch(
() => locale.value,
() => {
desWord.value = [
_this.t("home.f4"),
_this.t("home.f5"),
_this.t("home.f6"),
];
}
);
</script>
多语言:
页面展示:
组件库的table的title
模板:
<a-table :dataSource="dataSource" :columns="columns" />
js:
<script setup>
import i18n from "@/lang/index.js";
import { ref, watch} from "vue";
const locale = ref(i18n.global.locale);
const _this = i18n.global;
const dataSource = ref([]);
const columns = ref([
{
title: _this.t("home.f1"),//我的主页
dataIndex: "name",
key: "name",
},
{
title: _this.t("home.f7"),//平台
dataIndex: "age",
key: "age",
},
{
title: _this.t("home.f8"),//客服
dataIndex: "address",
key: "address",
},
]);
watch(
() => locale.value,
() => {
columns.value = [
{
title: _this.t("home.f1"),
dataIndex: "name",
key: "name",
},
{
title: _this.t("home.f7"),
dataIndex: "age",
key: "age",
},
{
title: _this.t("home.f8"),
dataIndex: "address",
key: "address",
},
];
}
);
</script>
展示: