Created
May 17, 2019 21:08
-
-
Save nfreear/933ec1ab2e199122cf330a02bcd3bb19 to your computer and use it in GitHub Desktop.
i18n / translation with Vue.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> <title> v-translate </title> | |
<style> body { margin: 2em auto; max-width: 30rem; } </style> | |
<div id="app"> | |
<h1> {{ 'i18n' | _ }} </h1> | |
<h2> {{ 'Hello World!' | _('en') }} </h2> | |
<h2 v-translate:lang.fr="'Hello World!'"></h2> | |
<translate :lang="'zh'" :elem="'h3'" >Hello World!</translate> | |
</div> | |
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> | |
<script> | |
const DEF_LANG = 'en'; | |
const TRANS = { | |
'i18n': { | |
en: 'Translation / i18n for Vue.js', | |
}, | |
'Hello World!': { | |
en: 'Hello World !!', | |
fr: 'Bonjour le monde!', | |
zh: '你好,世界', | |
} | |
} | |
function _translate (msgId, lang) { | |
let avail = TRANS[ msgId ]; | |
console.warn('_trans:', lang, TRANS, avail[ lang ]) | |
if (avail && lang in avail) { | |
return avail[ lang ]; | |
} | |
return msgId; | |
} | |
// ------------------------------------------------------------------ | |
Vue.component('translate', { | |
functional: true, | |
props: { | |
lang: { type: String, default: DEF_LANG }, | |
elem: { type: String, default: 'span' }, | |
}, | |
render (createElement, ctx) { | |
console.warn('translate.comp:', ctx.children[ 0 ].text, ctx.props.lang) | |
return createElement(ctx.props.elem, _translate(ctx.children[ 0 ].text, ctx.props.lang)); | |
} | |
}) | |
Vue.filter('_', function (msgId, lang) { | |
lang = lang || DEF_LANG; | |
console.warn('_.filter:', msgId, lang) | |
return _translate(msgId, lang) | |
}) | |
Vue.directive('translate', { | |
inserted: function (elem, binding) { | |
let m_lang = /v-translate:lang\.(\w+)/.exec(binding.rawName); | |
console.warn('translate.directive:', elem, binding, m_lang) | |
elem.innerText = _translate(binding.value, m_lang[ 1 ] || DEF_LANG) | |
} | |
}) | |
</script> | |
<script> | |
new Vue({ el: '#app' }) | |
</script> | |
<pre> | |
© Nick Freear, 17-May-2019. | |
* https://vuejs.org/v2/guide/custom-directive.html | |
* https://kazupon.github.io/vue-i18n/ | |
</pre> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment