Although I am aware that directly modifying the dom in vue.js is not recommended, I find that the alternatives would result in much messier and harder to maintain code.
The Challenge
Currently, with the use of vue-i18n, I need to dynamically move the currency symbol either in front or behind the price element depending on the selected language by the user. This applies to over 150 elements displaying prices on numerous pages throughout the site.
Possible Solutions
One option could be to apply a :class binding to each element that requires this change, however, this approach would involve adding multiple v-ifs, mapGetters, additional markup across all 15 pages where prices are displayed, as well as vuex logic. It might also involve using ::before and ::after in CSS to create separate classes for each language and include the symbol within the content property.
New Approach Under Consideration
Instead of cluttering the template with extra markup and v-if statements, I am considering utilizing a mounted hook within app.vue which would wait for the child view to be fully rendered before calling a function to append the currency symbol either before or after all elements with the priceItem class.
This method would still involve direct dom manipulation, but only after everything has been rendered.
Is there an alternative solution that could provide the simplicity I seek while adhering to Vue standards?
Sample Code (app.vue)
this.$nextTick(function () {
// Retrieve currently selected language from i18n
let lang = this.$i18n.locale;
// Obtain correct currency symbol for the selected language
let symbol = '';
switch (lang) {
case 'ko':
symbol = '₩';
break;
case 'en':
symbol = '$';
break;
case 'ja':
symbol = '¥';
break;
case 'zh':
symbol = '¥';
break;
case 'es':
symbol = '€';
break;
case 'ru':
symbol = '₽';
break;
}
// Append symbol after if language is Korean, else append before
if (lang !== 'ko') {
document
.querySelector('priceItem')
.insertAdjacentText('beforeBegin', symbol);
} else {
document
.querySelector('priceItem')
.insertAdjacentText('afterBegin', symbol);
}
});
UPDATE:
Upon further contemplation, it might be more appropriate to utilize a computed property so that the symbol can be reassigned whenever the user changes the language.