How can I define font-family
for my app based on user locale?
Let say user switch to ID
then I change font-family of my site body.
app.scss
As of sample I’ve added 3 fonts and try to use each of them based on selected locale
//use for "en" @font-face { font-family: Nunito; src: url('/fonts/Nunito/Nunito-Regular.ttf'); } //use for "id" @font-face { font-family: Righteous; src: url('/fonts/Righteous/Righteous-Regular.ttf'); } // use for "fa" @font-face { font-family: Dirooz; src: url('/fonts/dirooz/Dirooz.ttf'); }
any idea?
Advertisement
Answer
You can do it from within the Vue component triggering another method when the user selects a locale
Assume that you have @font-face defined in your css for all three
@font-face { font-family: Nunito; src: url('/fonts/Nunito/Nunito-Regular.ttf'); } //use for "id" @font-face { font-family: Righteous; src: url('/fonts/Righteous/Righteous-Regular.ttf'); } // use for "fa" @font-face { font-family: Dirooz; src: url('/fonts/dirooz/Dirooz.ttf'); }
Then in the Vue component
setFontFamily() { let styleTags = document.querySelectorAll('style'); if(this.initialStyleTagsCount < styleTags.length) { //Remove the previous style tag let lastStyle = styleTags[styleTags.length - 1]; document.head.removeChild(lastStyle); } let style = document.createElement('style'); //style.appendChild(document.createTextNode(` // @font-face { // font-family: ${this.fontFamily}; // src: url('${this.fontFamilyUrl}`); // }` //)); style.appendChild( document.createTextNode(`body { font-family: '${this.fontFamily}' }`) ); document.head.appendChild(style); }
You can have a lookup table for values of fontFamily and fontFamily url corresponding to the available locales within the component and probably computed properties for fontFamily & fontFamily url based on selected locale
data(){ return { //fonts: { // en: 'Nunito', url: '/fonts/Nunito/Nunito-Regular.ttf'}, // id: { fontFamily: 'Righteous', url: '/fonts/Righteous/Righteous-Regular.tt'}, // fa: { fontFamily: 'Dirooz', url: '/fonts/dirooz/Dirooz.ttf'} // }, fonts: { en: 'Nunito', id: 'Righteous', fa: 'Dirooz' }, initialStyleTagsCount: this.getStyleTagsCount() // other data properties } }, computed:{ //fontFamily() { // return this.fonts[this.locale]['fontFamily']; //}, //fontFamilyUrl() { // return this.fonts[this.locale]['url']; //}, fontFamily() { return this.fonts[this.locale]; } }, methods:{ getStyleTagsCount() { return document.querySelectorAll('style').length; } }