使用 vue-i18n 切換中英文

使用 vue-i18n 切換中英文

vue-i18n 倉庫地址:https://github.com/kazupon/vue-i18n

兼容性:

支持 Vue.js 2.x 以上版本

?

安裝方法:(此處只演示 npm)

npm install vue-i18n

?

使用方法:

1、在 main.js 中引入 vue-i18n (前提是要先引入 vue)

import VueI18n from 'vue-i18n'Vue.use(VueI18n)

?

2、準備本地的翻譯信息

復制代碼
const messages = {zh: {message: {hello: '好好學習,天天向上!'}},en: {message: {hello: 'good good study, day day up!'}}
}
復制代碼

?

3、創建帶有選項的 VueI18n 實例

const i18n = new VueI18n({locale: 'en', // 語言標識
    messages
})

?

4、把 i18n 掛載到 vue 根實例上

const app = new Vue({router,i18n,...App
}).$mount('#app')

?

5、在 HTML 模板中使用

<div id="app"><h1 style="font-size: 16px; text-align: center;">{{ $t("message.hello") }}</h1></div>

?

查看運行效果:

我們剛才選定的語言標識是 “en” 英語,現在改成 “zh” 中文,并查看效果

const i18n = new VueI18n({locale: 'zh', // 語言標識
    messages
})

這樣就可以輕松實現國際化了,實際開發中,頁面內容肯定是很多的,我們可以把對應語言的信息保存為不同的 json對象

復制代碼
const i18n = new VueI18n({locale: 'en',  // 語言標識
    messages: {'zh': require('./common/lang/zh'),'en': require('./common/lang/en')}
})
復制代碼

zh.js

復制代碼
// 注意:一定是 exports,不是 export,否則會報錯,報錯信息是下列的中的內容不是 string
module.exports = {message: {title: '運動品牌'},placeholder: {enter: '請輸入您喜歡的品牌'},brands: {nike: '耐克',adi: '阿迪達斯',nb: '新百倫',ln: '李寧'}
}
復制代碼

en.js

復制代碼
module.exports = {message: {title: 'Sport Brands'},placeholder: {enter: 'Please type in your favorite brand'},brands: {nike: 'Nike',adi: 'Adidas',nb: 'New Banlance',ln: 'LI Ning'}
}
復制代碼

接下來,在HTML 模板中使用,要特別注意在 js 中的國際化寫法

復制代碼
// HTML
<div id="app"><div style="margin: 20px;"><h1>{{$t("message.title")}}</h1><input style="width: 300px;" class="form-control" :placeholder="$t('placeholder.enter')"><ul><li v-for="brand in brands">{{brand}}</li></ul></div>
</div>// JS
data () {return {brands: [this.$t('brands.nike'), this.$t('brands.adi'), this.$t('brands.nb'), this.$t('brands.ln')]}},
復制代碼

查看編譯效果:

現在換成英文的:

在上面的操作中,我們都是通過手動修改 locale 的屬性值來切換語言,實際上,更希望瀏覽器自動識別,這里可以借助于 cookie

1、新建一個 cookie.js 文件,用于讀取cookie

復制代碼
function getCookie(name,defaultValue) {var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");if (arr = document.cookie.match(reg))return unescape(arr[2]);elsereturn defaultValue;
}export {getCookie
}
復制代碼

2、在 main.js 中引入這個js,并通過 PLAY_LANG 屬性來獲取瀏覽器的語言

復制代碼
const i18n = new VueI18n({locale: getCookie('PLAY_LANG','zh'),    // 語言標識
    messages: {'zh': require('./common/lang/zh'),'en': require('./common/lang/en')}
})
復制代碼

這里需要注意兩個極易出錯的地方:

(1)、將 $t() 寫成了 $()

(2)、json 中在同一個對象里有同名屬性

?

vue-i18n 提供了一個全局配置參數叫 “locale”,通過改變 locale 的值可以實現不同語種的切換

下面的案例借用了 Element UI 的彈窗樣式,上面的步驟不再贅述,直接上核心代碼

// template
<h2>{{$t('test')}}</h2>
<button type="button" class="btn btn-success" @click="changeLocale">中文/EN</button>        
復制代碼
// js方法
changeLocale () {this.$confirm(this.$t('layer.toggle'), this.$t('layer.tips'), {confirmButtonText: this.$t('button.ok'),cancelButtonText: this.$t('button.cancel'),type: 'warning'}).then(() => {let locale = this.$i18n.localelocale === 'zh' ? this.$i18n.locale = 'en' : this.$i18n.locale = 'zh'}).catch(() => {this.$message({type: 'info',})      })
},
復制代碼

效果:

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/387138.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/387138.shtml
英文地址,請注明出處:http://en.pswp.cn/news/387138.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ZooKeeper數據模型

Zookeeper的數據模型 層次化的目錄結構&#xff0c;命名符合常規文件系統規范&#xff08;Linux&#xff09; 每個節點在zookeeper中叫做znode,并且其有一個唯一的路徑標識 節點Znode可以包含數據和子節點(即子目錄)&#xff0c;但是EPHEMERAL類型的節點不能有子節點 Znod…

堆疊條形圖

堆疊條形圖 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.dates as mdates#解決能顯示中文 mpl.rcParams[font.sans-serif][SimHei] #指定默認字體 SimHei為黑體 mpl.rcParams[axes.unicode_minus]Fal…

spring boot 服務器常用

ps aux|grep tgcwll /opt/nginx/html sudo cp -r /tmp/tgcw/dist/* /opt/nginx/html/design sudo cp -r /tmp/tgcw/dist/* /opt/nginx/html springboot 啟動nohup java -jar tgcw-service-usermanagement-0.0.1-SNAPSHOT.jar --spring.profiles.activedemo > /dev/null 2&g…

PHP數組 轉 對象/對象 轉 數組

/*** 數組 轉 對象** param array $arr 數組* return object*/ function array_to_object($arr) {if (gettype($arr) ! array) {return;}foreach ($arr as $k > $v) {if (gettype($v) array || getType($v) object) {$arr[$k] (object)array_to_object($v);}}return (obj…

ZooKeeper編程01--RMI服務的多服務器管理

服務器端與客戶端都要用到&#xff1a; public interface ZkInfo {String ZK_CONNECTION_STRING "192.168.1.201:2181,192.168.1.202:2181,192.168.1.203:2181";int ZK_SESSION_TIMEOUT 5000;String ZK_REGISTRY_PATH "/registry";String ZK_PROVIDER_…

org.activiti.engine.ActivitiOptimisticLockingException updated by another transaction concurrently

org.activiti.engine.ActivitiOptimisticLockingException: Task[id5905010, name審核(市場部)] was updated by another transaction concurrentlyat org.activiti.engine.impl.db.DbSqlSession.flushUpdates(DbSqlSession.java:872)at org.activiti.engine.impl.db.DbSqlSess…

DataTable不能通過已刪除的行訪問該行的信息解決方法

使用dt.Rows[0]["name", DataRowVersion.Original]可以獲取轉載于:https://www.cnblogs.com/heyiping/p/10616640.html

ZooKeeper編程02--多線程的分佈式鎖

面向過程版&#xff1a; package distributedLockProcess;import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch;import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zoo…

01 Python變量和數據類型

Python變量和數據類型 1 數據類型 計算機&#xff0c;顧名思義就是可以做數學計算的機器&#xff0c;因此&#xff0c;計算機程序理所當然也可以處理各種數值。 但是&#xff0c;計算機能處理的遠不止數值&#xff0c;還可以處理文本、圖形、音頻、視頻、網頁等各種各樣的數…

初識Python-1

1&#xff0c;計算機基礎。 2&#xff0c;python歷史。 宏觀上&#xff1a;python2 與 python3 區別&#xff1a; python2 源碼不標準&#xff0c;混亂&#xff0c;重復代碼太多&#xff0c; python3 統一 標準&#xff0c;去除重復代碼。 3&#xff0c;python的環境。 編譯型&…

02 List、Tuple、Dict、Set

List 線性表 創建List&#xff1a; >>> classmates [Michael, Bob, Tracy] >>> L [Michael, 100, True] #可以在list中包含各種類型的數據 >>> empty_list [] #空List 按索引訪問List&#xff1a; >>> print L[0] #索引從0開始…

Jenkins的一些代碼

pipeline {agent anyenvironment { def ITEMNAME "erp"def DESTPATH "/home/ops/testpipe"def codePATH"/var/lib/jenkins/workspace/test_pipeline"}stages { stage(代碼拉取){steps {echo "checkout from ${ITEMNAME}"git url:…

利用layui前端框架實現對不同文件夾的多文件上傳

利用layui前端框架實現對不同文件夾的多文件上傳 問題場景&#xff1a; 普通的input標簽實現多文件上傳時&#xff0c;只能對同一個文件夾下的多個文件進行上傳&#xff0c;如果要同時上傳兩個或多個文件夾下的文件&#xff0c;是無法實現的。這篇文章就是利用layui中的插件&am…

ps、grep和kill聯合使用殺掉進程

ps、grep和kill聯合使用殺掉進程例如要殺掉hello這個進程&#xff0c;使用下面這個命令就能直接實現。ps -ef |grep hello |awk {print $2}|xargs kill -9這里是輸出ps -ef |grep hello 結果的第二列的內容然后通過xargs傳遞給kill -9,其實第二列內容就是hello的進程號&#xf…

03 控制語句

if語句 if age > 18 print your age is, age else print teenager Python代碼的縮進規則&#xff1a;具有相同縮進的代碼被視為代碼塊。 if age > 18 print adult elif age > 6 print teenager elif age > 3 print kid else print baby for循環 L [Adam, L…

yum 來安裝 nodejs

要通過 yum 來安裝 nodejs 和 npm 需要先給 yum 添加 epel 源&#xff0c;添加方法在 centos 添加epel和remi源 中##添加 epel 源 64位: rpm -ivh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm32位: rpm -ivh http://download.fedoraproj…

yzh的神仙題

U66905 zz題 考慮一個點權值被計算了多少次。。。不知 所以對未來承諾&#xff0c;方便直接算上總數&#xff01; 然后其實是給邊定向&#xff0c;即先刪除fa和son的哪一個 f[x][j]&#xff0c;會計算j次 無法轉移 f[x][j][k]&#xff0c;其中會從子樹計算k次。 當邊從兒子指向…

04 函數

內置函數 Python內置了很多有用的函數&#xff0c;可以直接調用。 要調用一個函數&#xff0c;需要知道函數的名稱和參數。 可以直接從Python的官方網站查看文檔&#xff1a;http://docs.python.org/2/library >>> abs(-20) >>> help(abs) >>>…

iview render的時候可以寫控件的基本格式

render: (h, params) > {return h(div, [h(Button, {props: {type: id,size: small},style: {marginRight: 5px},on: {click: () > {this.pojectshow(this.datatable[params.index].id)}}}, 詳情),h(Button, {props: {type: id,size: small},style: {marginRight: 5px},o…

ES6基本使用

var let 度可用于聲明變量. 區別&#xff1a;1、let&#xff1a;只在let命令所在代碼塊內有效 2、let 不存在變量提升&#xff08;內部影響不到外部&#xff09; var b [];for(var j0;j<10;j){let dj;b[j]function(){console.log(d);};}b[3]() //3 3、let 不允許在相同作用…