Adding text to several elements by class in Vue.js

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.

Answer №1

If you're searching for a fast fix in Vue, I successfully resolved my problem using this package:

https://github.com/vinayakkulkarni/vue-intl-numberformat

In my template, I implemented the following format:

<vue-intl-numberformat
   locale="en-IN"
   format-style="currency"
   :currency="getCurrency"
   :number="item.price"
 />

...

computed: {
   ...mapGetters(['getCurrency'])
}

Afterwards, I dynamically set the appropriate currency based on the selected language in i18n through a getter.

(In my vuex store)

  getCurrency: (state) => {
    let activeLang = i18n.locale
    let currency = ''

    switch (activeLang) {
      case 'en':
        currency = 'USD'
        break
      case 'ko':
        currency = 'KRW'
        break
      case 'ja':
        currency = 'JPY'
        break
      case 'es' || 'fr' || 'it':
        currency = 'EUR'
        break
      case 'zh':
        currency = 'CNY'
        break
      case 'ru':
        currency = 'RUR'
        break
    }
    state.currency = currency
    return state.currency
  }

This approach appears to be the most efficient solution thus far.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimal approach for integrating enum with Angular, Mongoose, and Node.js

When it comes to fetching values from MongoDB and displaying them with AngularJS, the process can be straightforward with Jade but becomes more complex with Angular. Here is how the data flows: An array of items is retrieved from MongoDB, each containin ...

Is it possible to utilize Babel for transpiling, importing, and exporting in the client, all without relying on Web

Is it possible to compile JSX and export variables through the global namespace using Babel? I'm not interested in setting up a Webpack server. I'm currently familiarizing myself with ES6, JSX, Babel, and React, and I find adding another librar ...

What steps can be taken to have Eslint/Prettier report errors and warnings within a CI environment?

Recently, I encountered an issue with my Vue app where I am using Eslint with Prettier. Even though I have set up a Github action to check the code style, running npm run lint -- --no-fix only logs the warnings and does not cause the workflow to fail. I r ...

What is the process for sending a parameter in getStaticProps within Next.js

Is there a way in NextJS to call an API when a user clicks the search button and display the relevant result? Thanks for your input! The API I'm currently utilizing is , with "Steak" referring to the specific food item of interest. In my development ...

Accessing a variable from an external JavaScript file using jQuery

Can someone help me out with this issue I'm facing? I am having trouble getting a string returned to a variable in my embedded Javascript code. token.js: function token () { return "mysecretstring"; } HTML Code: <!DOCTYPE html> <h ...

Error encountered: _moment2.default.date is not a recognized function within the React application

I keep encountering an issue when attempting to utilize a date from Moment.js in the constructor, componentWillMount, or componentDidMount. The error message I receive is: Uncaught TypeError: _moment2.default.date is not a function It's worth noting ...

Creating a fixed navigation bar that stays at the top of the page when scrolling

I am trying to create a navigation bar similar to the one seen on W3School's website. I would like the navigation bar to overlap the header when scrolling down, and for the header to appear above the nav bar when scrolling back to the top. Despite m ...

recurring issues with time outs when making ajax requests

During the development of my website, I tested it as localhost. Now that it's nearly complete, I switched to using my local IP address and noticed that about 30% of my ajax calls result in time out errors or 'failed to load resource errors'. ...

Troubleshooting alignment problems with a responsive gallery (Bootstrap-gallery & justifyGallery)

Looking to showcase a gallery of images using jquery-justifyGallery and bootstrap-gallery. Want to display 4 images in a row, but running into issues when trying to display 5 images where the last image in the row ends up with a larger width. Bootstrap has ...

Click to be redirected to the same page on a different store

I have been working on a Shopify project where I implemented a pop-up that appears when the page loads, prompting users to choose between the US and UK websites. Once a user clicks on one of the options, the pop-up either closes (UK) or redirects them to ...

ExpressJS: How to resolve the undefined error in Express session

After using express-generator to create my project, I installed the express-session package. Below is how express-session is ordered in my app: app.js var expressSession = require('express-session'); app.use(logger('dev')); app.use( ...

Changing the value of a previous TD element using Javascript

My page features a button that, when clicked, triggers a function to change the value in the previous TD element from "No" to "Yes". Here is the HTML snippet: <tr class="odd"> <td class="">13.00</td> <td class="">DDR</td> ...

Accordion Functionality in Vue with Animation Effects

I'm struggling to implement a smooth transition for the Accordion component, but unfortunately it's not working as expected. Everything else is functioning correctly except for the animation. template: <div class="accordion"> <di ...

Navigating through arrays to access nested objects

Currently, I am attempting to retrieve a specific field within a nested array using the following code: var array1 = []; const data = { [userId]: [{ id: id, name: fullName, email: userEmail }, ], ...

Discovering the source of a request payload

Is it possible for me to locate the source of a single item in the request payload using Chrome DevTools, even though I am unsure how it was created? Is there any way for me to find this information? ...

Using an image as the background for a three.js scene may cause it to appear distorted

I am struggling with setting an image as a background for my scene without it becoming blurry. I have attempted to use the following code: textureLoader.load("images/background/space.png", function(t) { scene.background = t; }); The problem arises when ...

Discover the steps to showcase a specific option from a select list at the top row through VueJs

Below is the code to iterate through the elements of teamLeaderOfWithDescendants <option :value="item.user_id" v-for="item in teamLeaderOfWithDescendants"> {{item.user_full_name}} </option> Is there a way to prioritize the row where item.u ...

What is the best way to extract parameters from a JSON object?

Here is the complete code: $.post('test.php', { id: id },function (data) { console.log(data); var Server = data.response.server; var Photo = data.response.photo; console.log(Server); console.log(Photo); }); When I receive data I get JSON data ...

Best practice for integrating configuration settings into a Redux application

One essential step before launching my application is to read the config.json file. This file contains the URLs to my backend services, which will be utilized in my Redux action creators. I have contemplated two different approaches: Fetching the JSON a ...

Issue with Javascript variables

In Javascript, I have an array of strings that I need to use for loading images on my page through AJAX. After each image is loaded, there are additional tasks to be performed which include sending a HTTP request to delete the image. Below is the code I c ...