在vue页面写i18n国际化文件,不使用引入-切换

1 篇文章 0 订阅
1 篇文章 0 订阅

1:下载i18n插件

npm install vue-i18n
npm install @intlify/vue-i18n-loader

2:在main.js中注册(都是基本操作)

// main.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import App from './App.vue'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'cn', //切换应该是操作这个 我没写过我百度下去
  messages: {}
})

new Vue({
  i18n,
  el: '#app',
  render: h => h(App)
})

3:webpack,配置 -这个非常重要不这么写就不生效,我不懂理论,我只会用…

const path = require('path')
const VueLoaderPlugin = require('vue-loader/lib/plugin')

module.exports = {
  mode: 'development',
  entry: path.resolve(__dirname, './main.js'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/dist/'
  },
  devServer: {
    stats: 'minimal',
    contentBase: __dirname
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.js$/,
        loader: 'babel-loader'
      },
      //  主要看这里 !!!!!!!!!!!!!!!!!!!!! i18n
      //  customBlocks 对应的 rule
      {
        // 使用 resourceQuery 来为一个没有 lang 的自定义块匹配一条规则
        // 如果找到了一个自定义块的匹配规则,它将会被处理,否则该自定义块会被默默忽略
        resourceQuery: /blockType=i18n/,
        // Rule.type 设置类型用于匹配模块。它防止了 defaultRules 和它们的默认导入行为发生
        type: 'javascript/auto',
        // 这里指的是 vue-i18n-loader
        use: [path.resolve(__dirname, '../lib/index.js')]// loader: '@intlify/vue-i18n-loader' 我项目是这么写的 两个二选一把 看看哪个能跑起来
      }
    ]
  },
  plugins: [new VueLoaderPlugin()]
}

4:页面使用


<template>
  <p>{{ $t('hello') }}</p>
</template>

<script>
// App.vue
export default {
  name: 'App'
}
</script>

<i18n locale="en">
{
  "hello": "Want to go to work without an interview"
}
</i18n>

<i18n locale="cn" >
{
  "hello": "想不面试就上班"
}
</i18n>
// 或者
<i18n locale="cn" lang="yaml">
  hello: 想不面试就上班
</i18n>
<i18n locale="en" lang="yaml">
  hello: Want to go to work without an interview
</i18n>

5:切换

change(){
	if(this.$i18n.locale == 'en'){
		this.$i18n.locale = 'zh'
	}else{
		this.$i18n.locale = 'en'
	}
}

6:JS文件中使用I18n,先建一个文件

import { getCurrentInstance } from '@vue/composition-api'
function getVm() {
  return getCurrentInstance()?.proxy
}

export function useRoute() {
  return getVm()?.$route
}

export function useRouter() {
  return getVm()?.$router
}

export function useI18n() {
  return getVm()?.$i18n
}
export function useStore() {
  return getVm()?.$store
}

7:导入使用

import { useI18n, useStore } from'文件路径'


const i18n = useI18n()
i18n.t('tab')
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值