Vue3.0 在组件外使用 VueI18n 的问题

通常将写在setup里面的代码写在外面会报错

Must be called at the top of a `setup`

意思是必须写在setup里面

要将 i18n 与 Vue 3 的组合 API 一起使用,但在组件的 setup() 之外,需要这么写

// locales/setupI18n.ts

import { App } from 'vue';
import { createI18n } from 'vue-i18n'; // 引入vue-i18n组件
import { messages } from './config';
import globalConfig from '@/config/index';

const {
  setting: { lang: defaultLang },
} = globalConfig;

// 注册i8n实例并引入语言文件
const localeData = {
  legacy: false, // 使用CompotitionAPI必须添加这条.
  locale: defaultLang,
  messages,
  globalInjection: true,
};

export const i18n = createI18n(localeData);

// setup i18n instance with glob
export const setupI18n = {
  install(app: App) {
    app.use(i18n);
  },
};

这里是关键写法


//某个组合式js文件

//报错写法 Uncaught SyntaxError: Must be called at the top of a `setup` 
//import { useI18n } from 'vue-i18n'
//const { t } = useI18n() 

//正确写法
import { i18n } from '@/locales/setupI18n';
const { t } = i18n.global;
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3.0中,父组件向子组件传递参数有多种方式。一种方式是通过props进行传递,另一种方式是通过自定义事件进行传递。 对于使用props进行传递的情况,父组件可以在子组件标签中定义一个属性,然后在子组件使用props接收该属性的值。例如,父组件可以这样定义子组件的标签:`<son :type="father"></son>`,然后在子组件使用props接收父组件传递的值,例如:`props: { type: [String, Number },` [2。 对于通过自定义事件进行传递的情况,父组件可以在子组件的标签中定义一个自定义事件,并在子组件使用defineEmits来向父组件传递参数。例如,父组件可以这样定义子组件的标签:`<sonOne msg="我是父组件的msg" @get-child-data="getChildData"></sonOne>`,然后在子组件使用defineEmits定义一个事件,并通过emits触发该事件来向父组件传递参数。例如,在子组件中可以这样定义事件并触发:`const emits = defineEmits(); emits('getChildData', num);`,然后在父组件中可以通过定义一个方法来接收子组件传递的参数,并进行处理。。同时,在子组件使用reactive来定义响应式数据,以便接收父组件传递的参数。例如,在子组件中可以这样定义响应式数据:`const state = reactive({ fatherData: props.msg })` [3。 总结来说,在Vue 3.0中,父组件可以通过props或自定义事件来向子组件传递参数,然后子组件可以使用props接收父组件传递的值,或使用defineEmits和emits来触发自定义事件并向父组件传递参数。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [vue2和vue3 父子组件传参及区别](https://blog.csdn.net/weixin_50370865/article/details/128413462)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [vue3.0父子组件传递参数](https://blog.csdn.net/weixin_49596018/article/details/118700349)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值