import { useToast } from "vue-toastification";
import { useI18n } from "vue-i18n";
export default function useToastMsg(message, type) {
const { t } = useI18n();
const toast = useToast()
if (type == "success") {
return toast.success(t(`${message}`))
} else if (type == "error") {
return toast.error(t(`${message}`))
}
}
Run Code Online (Sandbox Code Playgroud)
我试图在行动发生后在商店中使用此功能。商店.js
import useToast from "@/composables/toast"
在行动功能:
useToast("submit", "success")
错误信息:
Uncaught (in promise) SyntaxError: Must be called at the top of a 设置 function
我该如何解决这个问题?
小智 19
这让我有些头疼。但最终我确实想出了一个超级简单的解决方案。
第一步:像这样初始化 i18n:
/* /utils/i18n.ts */
import { createI18n } from 'vue-i18n';
import messages from 'src/i18n';
const instance = createI18n({
locale: 'en-US',
messages,
});
export default instance;
export const i18n = instance.global;
Run Code Online (Sandbox Code Playgroud)
第 2 步:将上面的 i18n 实例添加到您的 Vue 应用程序中,如下所示:
import { createApp } from 'vue';
import i18nInstance from '/utils/i18n.ts'
const app = createApp({
// something vue options here ...
})
app.use(i18nInstance)
app.mount('#app')
Run Code Online (Sandbox Code Playgroud)
这是迄今为止您常用的 i18n 设置。现在,当你想在 pinia 中使用它时,你可以这样做:
import { defineStore } from 'pinia';
import { i18n } from '/utils/i18n';
const useStore = defineStore({
id: 'StoreApp',
state: () => {},
getters: {
getSomeTranslatedString() => i18n.t('String to be translated')
},
actions: {}
});
export default useStore;
Run Code Online (Sandbox Code Playgroud)
useI18n()只能在setup()函数的顶部使用,因为它需要使用 Composition API 的inject().
解决方法是传递$t()给useToastMsg():
// composables/toast.js
export default function useToastMsg(t, message, type) {
//...
return toast.success(t(`${message}`))
}
Run Code Online (Sandbox Code Playgroud)
<template>
<button @click="sayHello($t)">{{ $t('action.hello') }}</button>
</template>
<script>
import { defineComponent } from 'vue'
import { useStore } from '@/store'
import { mapActions } from 'pinia'
export default defineComponent({
methods: {
...mapActions(useStore, ['sayHello']),
},
})
</script>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9011 次 |
| 最近记录: |