Vue3.0在组件外使用VueI18n的情况是什么
本篇内容主要讲解“Vue3.0在组件外使用VueI18n的情况是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue3.0在组件外使用VueI18n的情况是什么”吧!
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;
vue3使用vue-i18n国际化(多语言转换)
提醒:vue3要使用vue-i18n必须要9以上的版本 npm install vue-i18n@9.2.2
具体操作
在src文件下新建一个lang文件夹,里面分别建好“cn.js”、“en.js”、 “index.js”三个文件
cn.js和en.js中存放对应的翻译,例如:
const messages = {
home: {
title: 'Book Store',
hint: 'Computer Science And Software Engineering',
guessYouLike: 'Guess You Like',
}
}
export default messages
const messages = {
home: {
title: '书城',
hint: '计算机科学和软件工程',
guessYouLike: '猜你喜欢'
}
}
export default messages
index.js中存放如下模板
import { createI18n } from 'vue-i18n'
import en from './en'
import cn from './cn'
const messages = {
en, cn
}
const localeData = {
legacy: false, // composition API
globalInjection: true, //全局生效$t
locale: cn, // 默认cn翻译
messages
}
export function setupI18n (app) {
const i18n = createI18n(localeData)
app.use(i18n)
}
然后在main.js中使用setupI18n
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { setupI18n } from './lang/index'
const app = createApp(App)
app.use(store).use(router).mount('#app')
setupI18n(app)
使用的时候只需要在对应的地方写上 {{ $t("home.title") }} 就能使用了,需要特别注意的是必须使用$t开头,不能单独用t,如果需要单独用t的话需要其他的配置,直接用$t也比较方便,关于怎么单独使用t这里就不细说了
<span class="ebook-popup-title-text">
{{$t("home.title")}}
</span>
相关内容
这些是最新的
热门排行
- THINKPHP5+GatewayWorker+Workerman 开发在线客服系统
- 在手机浏览器网页中点击链接跳转到微信界面的方法
- 尊云网站目录系统 ThinkPHP5网站分类目录程序 v2.2.221011
- CentOS 7安装shadowsock(一键安装脚本)
- AdminTemplate 基于LayUI 2.4.5实现的网站后台管理模板
- 用NW.js(node-webkit)开发多平台的桌面客户端
- PHP生成随机昵称/用户名
- THINKPHP5网站分类目录程序 尊云网站目录系统
- 织梦(DEDECMS)微信支付接口 微信插件
- 基于LayUI开发的 网站后台管理模板 BeginnerAdmin
- 响应式后台网站模板 - AMA.ADMIN
- layuiAdmin后台管理模板 Iframe版
- LayUI 1.0.9 升级 至 LayUI 2.1.4 方法
- 简洁清爽的会员中心模板
- jQuery幸运大转盘抽奖活动代码