Dynamic Translate with Special Formatting

Well… I believe you already have a preliminary understanding about using vue-i18n . Let’s try to make Dynamic Translate .

In vue-i18n , It can provide Name Formatting and List Formatting .

Suppose the scenario is show different Text in the same message dynamically from some business logic return value.

For Example :

// Dynamic Text

// [alert], [remind], [error] 1. You have alert message. // If return id is 0

2. You have remind message. // If return id is 1

3. You have error message. // If return id is 2

Step 1

Define the Dynamic Text of Return ID in locale json file

// en_US.json {

"notice": {

"msg": "You have {noticeType} message"

},

"type": [

"text": "alert",

"text": "remind",

"text": "error"

]

} // zh_CN.json {

"notice": {

"msg": "你有{noticeType}短讯"

},

"type": [

"text": "警报",

"text": "提醒",

"text": "错误"

]

}

Step 2

Go back to component (.vue)

// In JS Part data() {

// From business logic to get notice type id

// 0 = alert, 1 = remind, 2 = error

let num = 2

return {

noticeTypeText: num

}

}

// In HTML DOM Part $t('lang.notice', {

'noticeType': $t(`lang.type[${noticeTypeText}].text`)

})

Final

In en_US environment,

If num = 0 , the message show You have alert message .

If num = 1 , the message show You have remind message .

If num = 2 , the message show You have error message .

In zh_CN environment

If num = 0 , the message show 你有警报短讯.

If num = 1 , the message show 你有提醒短讯.

If num = 2 , the message show 你有错误短讯.

Extended Study