增加格式化器演示

This commit is contained in:
wxzhang 2022-08-10 21:41:58 +08:00
parent 06d15633ac
commit baa7bc569c
11 changed files with 117 additions and 63 deletions

View File

@ -12,38 +12,53 @@ export default {
components: { China }, components: { China },
data() { data() {
return { return {
date1: new Date(), NOW: null//new Date()
date2: "2022/12/3 19:08:12",
date3: 1659872118897,
} }
} }
} }
</script> </script>
<template> <template>
<div style="padding:16px;border:1px red solid;line-height:120%;margin:0 auto;margin-bottom:16px;width:600px;"> <div style="padding:16px;border:1px red solid;line-height:120%;margin:0 auto;margin-bottom:16px;width:600px;text-align:left;">
<p>{{ t("现在是{ value | date }", date1) }} </p> <table>
<p>{{ t("现在是{ value | shortdate }", date2) }} </p> <thead>
<p>{{ t("现在是{ value | time }", date3) }} </p> <tr style="font-weight:bold;">
<p>{{ t("现在是{ value | shorttime }", date3) }} </p> <td style="width:200px;">格式化器</td>
<p>{{ t("现在是{ value | year }", date3) }} </p> <td>内容</td>
<p>{{ t("现在是{ value | month }", date3) }} </p> </tr>
<p>{{ t("现在是{ value | day }", date3) }} </p> </thead>
<p>{{ t("现在是{ value | weekdayValue }", date3) }} </p> <tbody>
<p>{{ t("现在是{ value | weekday }", date3) }} </p> <tr><td colspan="2" ><b>日期</b></td></tr>
<p>{{ t("现在是{ value | shortWeekday }", date3) }} </p> <tr><td>默认</td><td>{{ t("现在是{ value }", NOW) }}</td></tr>
<p>{{ t("现在是{ value | monthName }", date3) }} </p> <tr><td>date</td><td>{{ t("现在是{ value | date }", NOW) }}</td></tr>
<p>{{ t("现在是{ value | shorMonthName }", date3) }} </p> <tr><td>shortdate</td><td>{{ t("现在是{ value | shortdate }", NOW) }}</td></tr>
<p>{{ t("现在是{ value | hour }", date3) }} </p> <tr><td>time</td><td>{{ t("现在是{ value | time }", NOW) }}</td></tr>
<p>{{ t("现在是{ value | hour12 }", date3) }} </p> <tr><td>shorttime</td><td>{{ t("现在是{ value | shorttime }", NOW) }}</td></tr>
<p>{{ t("现在是{ value | minute }", date3) }} </p> <tr><td>year</td><td>{{ t("现在是{ value | year }", NOW) }}</td></tr>
<p>{{ t("现在是{ value | second }", date3) }} </p> <tr><td>month</td><td>{{ t("现在是{ value | month }", NOW) }}</td></tr>
<p>{{ t("现在是{ value | millisecond }", date3) }} </p> <tr><td>day</td><td>{{ t("现在是{ value | day }", NOW) }}</td></tr>
<p>{{ t("现在是{ value | timestamp }", date3) }} </p> <tr><td>weekdayValue</td><td>{{ t("现在是{ value | weekdayValue }", NOW) }}</td></tr>
<p>{{ t("商品价格:{ value | currency }", 854) }} </p> <tr><td>weekday</td><td>{{ t("现在是{ value | weekday }", NOW) }}</td></tr>
<p>{{ t("商品价格:{ value | currency("==","元整",3) }", 854) }} </p> <tr><td>shortWeekday</td><td>{{ t("现在是{ value | shortWeekday }", NOW) }}</td></tr>
<p>{{ t("商品价格:{ value | currency }", 874312.33) }} </p> <tr><td>monthName</td><td>{{ t("现在是{ value | monthName }", NOW) }}</td></tr>
<p>{{ t("商品价格:{ value | capitalizeCurrency }", 874312.33) }} </p> <tr><td>shorMonthName</td><td>{{ t("现在是{ value | shorMonthName }", NOW) }}</td></tr>
<tr><td colspan="2" ><b>时间</b></td></tr>
<tr><td>hour</td><td>{{ t("现在是{ value | hour }", NOW) }}</td></tr>
<tr><td>hour12</td><td>{{ t("现在是{ value | hour12 }", NOW) }}</td></tr>
<tr><td>minute</td><td>{{ t("现在是{ value | minute }", NOW) }}</td></tr>
<tr><td>second</td><td>{{ t("现在是{ value | second }", NOW) }}</td></tr>
<tr><td>millisecond</td><td>{{ t("现在是{ value | millisecond }", NOW) }}</td></tr>
<tr><td>timestamp</td><td>{{ t("现在是{ value | timestamp }", NOW) }}</td></tr>
<tr><td colspan="2" ><b>货币</b></td></tr>
<tr><td>currency-cny</td><td>{{ t("商品价格:{ value | currency('CNY','元整',3)}", 788741) }}</td></tr>
<tr><td>currency</td><td>{{ t("商品价格:{ value | currency }", 788741) }}</td></tr>
<tr><td>capitalizeCurrency</td><td>{{ t("商品价格:{ value | capitalizeCurrency }", 788741) }}</td></tr>
<tr><td>capitalizeCurrency</td><td>{{ t("商品价格:{ value | capitalizeCurrency(true) }", 788741.35) }}</td></tr>
<tr><td colspan="2" ><b>数字</b></td></tr>
<tr><td>number</td><td>{{ t("商品数量:{ value | number }", 1875109.987) }}</td></tr>
</tbody>
</table>
</div> </div>
</template> </template>

View File

@ -24,6 +24,9 @@ export default {
"23": "Now is { value | millisecond }", "23": "Now is { value | millisecond }",
"24": "Now is { value | timestamp }", "24": "Now is { value | timestamp }",
"25": "Price: { value | currency }", "25": "Price: { value | currency }",
"26": "Price: { value | currency(\"==", "26": "Price: { value | capitalizeCurrency }",
"27": "Price: { value | capitalizeCurrency }" "27": "Now is { value }",
"28": "Price: { value | currency('CNY','元整',3)}",
"29": "Price:{ value | capitalizeCurrency(true) }",
"30": "Count: { value | number }"
} }

View File

@ -24,6 +24,9 @@ export default {
"现在是{ value | millisecond }": 23, "现在是{ value | millisecond }": 23,
"现在是{ value | timestamp }": 24, "现在是{ value | timestamp }": 24,
"商品价格:{ value | currency }": 25, "商品价格:{ value | currency }": 25,
"商品价格:{ value | currency(\"==": 26, "商品价格:{ value | capitalizeCurrency }": 26,
"商品价格:{ value | capitalizeCurrency }": 27 "现在是{ value }": 27,
"商品价格:{ value | currency('CNY','元整',3)}": 28,
"商品价格:{ value | capitalizeCurrency(true) }": 29,
"商品数量:{ value | number }": 30
} }

View File

@ -13,11 +13,11 @@ const scopeSettings = {
"languages": [ "languages": [
{ {
"name": "zh", "name": "zh",
"title": "zh" "title": "中文"
}, },
{ {
"name": "en", "name": "en",
"title": "en" "title": "英文"
} }
], ],
"defaultLanguage": "zh", "defaultLanguage": "zh",
@ -28,7 +28,7 @@ const scopeSettings = {
// 语言作用域 // 语言作用域
const scope = new i18nScope({ const scope = new i18nScope({
...scopeSettings, // languages,defaultLanguage,activeLanguage,namespaces,formatters ...scopeSettings, // languages,defaultLanguage,activeLanguage,namespaces,formatters
id: "vueapp", // 当前作用域的id自动取当前工程的package.json的name id: "vueapp", // 当前作用域的id自动取当前工程的package.json的name
default: defaultMessages, // 默认语言包 default: defaultMessages, // 默认语言包
messages : activeMessages, // 当前语言包 messages : activeMessages, // 当前语言包
idMap:messageIds, // 消息id映射列表 idMap:messageIds, // 消息id映射列表

View File

@ -2,11 +2,11 @@
"languages": [ "languages": [
{ {
"name": "zh", "name": "zh",
"title": "zh" "title": "中文"
}, },
{ {
"name": "en", "name": "en",
"title": "en" "title": "英文"
} }
], ],
"defaultLanguage": "zh", "defaultLanguage": "zh",

View File

@ -149,16 +149,34 @@
"components\\formatters.vue" "components\\formatters.vue"
] ]
}, },
"商品价格:{ value | currency(\"==": {
"en": "Price: { value | currency(\"==",
"$file": [
"components\\formatters.vue"
]
},
"商品价格:{ value | capitalizeCurrency }": { "商品价格:{ value | capitalizeCurrency }": {
"en": "Price: { value | capitalizeCurrency }", "en": "Price: { value | capitalizeCurrency }",
"$file": [ "$file": [
"components\\formatters.vue" "components\\formatters.vue"
] ]
},
"现在是{ value }": {
"en": "Now is { value }",
"$file": [
"components\\formatters.vue"
]
},
"商品价格:{ value | currency('CNY','元整',3)}": {
"en": "Price: { value | currency('CNY','元整',3)}",
"$file": [
"components\\formatters.vue"
]
},
"商品价格:{ value | capitalizeCurrency(true) }": {
"en": "Price:{ value | capitalizeCurrency(true) }",
"$file": [
"components\\formatters.vue"
]
},
"商品数量:{ value | number }": {
"en": "Count: { value | number }",
"$file": [
"components\\formatters.vue"
]
} }
} }

View File

@ -22,7 +22,7 @@
day : value => toDate(value).getDate(), day : value => toDate(value).getDate(),
weekdayValue : value => toDate(value).getDay(), weekdayValue : value => toDate(value).getDay(),
weekday : value => ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][toDate(value).getDay()], weekday : value => ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][toDate(value).getDay()],
shortWeekday : value => ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur"][toDate(value).getDay()], shortWeekday : value => ["Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat"][toDate(value).getDay()],
monthName : value => ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][toDate(value).getMonth()], monthName : value => ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][toDate(value).getMonth()],
shorMonthName : value => ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"][toDate(value).getMonth()], shorMonthName : value => ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"][toDate(value).getMonth()],
// 时间 // 时间
@ -34,7 +34,7 @@
timestamp : value => toDate(value).getTime(), timestamp : value => toDate(value).getTime(),
// 货币 // 货币
// 常规货币形式 $111,233.33 // 常规货币形式 $111,233.33
currency: (value, prefix = "$",suffix="", division = 3,precision = 2) => toCurrency(value, { division, prefix, precision,suffix }), currency : (value, prefix = "$",suffix="", division = 3,precision = 2) => toCurrency(value, { division, prefix, precision,suffix }),
// 数字,如,使用分割符 // 数字,如,使用分割符
number: (value, division = 3,precision = 0) => toCurrency(value, { division, precision}) number : (value, division = 3,precision = 0) => toCurrency(value, { division, precision})
} }

View File

@ -14,7 +14,7 @@ module.exports = {// 简体中文
// 日期 // 日期
date : value => `${value.getFullYear()}${value.getMonth() + 1}${value.getDate()}`, date : value => `${value.getFullYear()}${value.getMonth() + 1}${value.getDate()}`,
weekday : value => CN_WEEK_DAYS[toDate(value).getDay()], weekday : value => CN_WEEK_DAYS[toDate(value).getDay()],
shortWeekDay : value => CN_SHORT_WEEK_DAYS[toDate(value).getDay()], shortWeekday : value => CN_SHORT_WEEK_DAYS[toDate(value).getDay()],
monthName : value => CN_MONTH_NAMES[toDate(value).getMonth()], monthName : value => CN_MONTH_NAMES[toDate(value).getMonth()],
shorMonthName: value => CN_SHORT_MONTH_NAMES[toDate(value).getMonth()], shorMonthName: value => CN_SHORT_MONTH_NAMES[toDate(value).getMonth()],
// 时间 // 时间

View File

@ -285,19 +285,19 @@ function getFormatter(scope,activeLanguage,name){
* @param {*} value * @param {*} value
* @param {*} formatters 多个格式化器顺序执行前一个输出作为下一个格式化器的输入 * @param {*} formatters 多个格式化器顺序执行前一个输出作为下一个格式化器的输入
*/ */
function executeFormatter(value,formatters){ function executeFormatter(value,formatters,scope){
if(formatters.length===0) return value if(formatters.length===0) return value
let result = value let result = value
try{ try{
for(let formatter of formatters){ for(let formatter of formatters){
if(typeof(formatter) === "function") { if(typeof(formatter) === "function") {
result = formatter(result) result = formatter.call(scope,result)
}else{// 如果碰到无效的格式化器,则跳过过续的格式化器 }else{// 如果碰到无效的格式化器,则跳过过续的格式化器
return result return result
} }
} }
}catch(e){ }catch(e){
console.error(`Error while execute i18n formatter for ${value}: ${e.message} ` ) //console.error(`Error while execute i18n formatter for ${value}: ${e.message} ` )
} }
return result return result
} }
@ -308,11 +308,6 @@ function executeFormatter(value,formatters){
* [[格式化器名称,[参数,参数,...]][格式化器名称,[参数,参数,...]]]格式化器转化为 * [[格式化器名称,[参数,参数,...]][格式化器名称,[参数,参数,...]]]格式化器转化为
* 格式化器的调用函数链 * 格式化器的调用函数链
* *
*
*
*
*
*
* @param {*} scope * @param {*} scope
* @param {*} activeLanguage * @param {*} activeLanguage
* @param {*} formatters * @param {*} formatters
@ -363,7 +358,7 @@ function getFormattedValue(scope,activeLanguage,formatters,value){
formatterFuncs.splice(0,0,defaultFormatter) formatterFuncs.splice(0,0,defaultFormatter)
} }
// 3. 执行格式化器 // 3. 执行格式化器
value = executeFormatter(value,formatterFuncs) value = executeFormatter(value,formatterFuncs,scope)
return value return value
} }
@ -432,6 +427,9 @@ const defaultLanguageSettings = {
datetime:{ datetime:{
}, },
currency:{
}
} }
function isMessageId(content){ function isMessageId(content){
@ -501,9 +499,6 @@ function translate(message) {
}) })
} }
// 3. 取得翻译文本模板字符串 // 3. 取得翻译文本模板字符串
if(activeLanguage === scope.defaultLanguage){ if(activeLanguage === scope.defaultLanguage){

View File

@ -32,11 +32,11 @@ module.exports = class i18nScope {
languages: options.languages, languages: options.languages,
}) })
} }
this.global = globalThis.VoerkaI18n this._global = globalThis.VoerkaI18n
this._mergePatchedMessages() this._mergePatchedMessages()
this._patch(this._messages,this.activeLanguage) this._patch(this._messages,this.activeLanguage)
// 正在加载语言包标识 // 正在加载语言包标识
this._loading=false this._refreshing=false
// 在全局注册作用域 // 在全局注册作用域
this.register(callback) this.register(callback)
} }
@ -60,7 +60,6 @@ module.exports = class i18nScope {
get loaders(){return this._loaders} get loaders(){return this._loaders}
// 引用全局VoerkaI18n配置注册后自动引用 // 引用全局VoerkaI18n配置注册后自动引用
get global(){return this._global} get global(){return this._global}
set global(value){this._global = value}
/** /**
* 在全局注册作用域 * 在全局注册作用域
* @param {*} callback 注册成功后的回调 * @param {*} callback 注册成功后的回调
@ -102,10 +101,14 @@ module.exports = class i18nScope {
registerDefaultLoader(fn){ registerDefaultLoader(fn){
this.global.registerDefaultLoader(fn) this.global.registerDefaultLoader(fn)
} }
_getLanguage(lang){
let index = this._languages.findIndex(lng=>lng.name==lang)
if(index!==-1) return this._languages[index]
}
/** /**
* 回退到默认语言 * 回退到默认语言
*/ */
_fallback(){ _fallback(newLanguage){
this._messages = this._default this._messages = this._default
this._activeLanguage = this.defaultLanguage this._activeLanguage = this.defaultLanguage
} }
@ -114,7 +117,7 @@ module.exports = class i18nScope {
* @param {*} newLanguage * @param {*} newLanguage
*/ */
async refresh(newLanguage){ async refresh(newLanguage){
this._loading = Promise.resolve() this._refreshing = true
if(!newLanguage) newLanguage = this.activeLanguage if(!newLanguage) newLanguage = this.activeLanguage
// 默认语言,默认语言采用静态加载方式,只需要简单的替换即可 // 默认语言,默认语言采用静态加载方式,只需要简单的替换即可
if(newLanguage === this.defaultLanguage){ if(newLanguage === this.defaultLanguage){
@ -131,7 +134,8 @@ module.exports = class i18nScope {
this._activeLanguage = newLanguage this._activeLanguage = newLanguage
await this._patch(this._messages,newLanguage) await this._patch(this._messages,newLanguage)
}else if(typeof(this.global.defaultMessageLoader) === "function"){// 如果该语言没有指定加载器,则使用全局配置的默认加载器 }else if(typeof(this.global.defaultMessageLoader) === "function"){// 如果该语言没有指定加载器,则使用全局配置的默认加载器
this._messages = await this.global.loadMessagesFromDefaultLoader(newLanguage,this) const loadedMessages = await this.global.loadMessagesFromDefaultLoader(newLanguage,this)
this._messages = Object.assign({},this._default,loadedMessages)
this._activeLanguage = newLanguage this._activeLanguage = newLanguage
}else{ }else{
this._fallback() this._fallback()
@ -139,6 +143,8 @@ module.exports = class i18nScope {
}catch(e){ }catch(e){
console.warn(`Error while loading language <${newLanguage}> on i18nScope(${this.id}): ${e.message}`) console.warn(`Error while loading language <${newLanguage}> on i18nScope(${this.id}): ${e.message}`)
this._fallback() this._fallback()
}finally{
this._refreshing = false
} }
} }
/** /**

View File

@ -41,6 +41,19 @@
return false return false
} }
} }
/**
* 当value= null || undefined || "" || [] || {} 时返回true
* @param {*} value
* @returns
*/
function isNothing(value){
if(["boolean","function"].includes(typeof(value))) return false
if(value=="") return true
if(value==undefined) return true
if(Array.isArray(value) && value.length==0) return true
if(typeof(value)=="object" && Object.keys(value).length==0) return true
return false
}
/** /**
* 深度合并对象 * 深度合并对象
@ -172,6 +185,7 @@ function relativeTime(value, rel){
module.exports ={ module.exports ={
isPlainObject, isPlainObject,
isNumber, isNumber,
isNothing,
deepMerge, deepMerge,
deepMixin, deepMixin,
getDataTypeName, getDataTypeName,