How to integrate Vue i18 currency with a third part API?

39 Views Asked by At

I'm using Vue.js I18 for localization and utilizing currency localization as well. My application is connected to a third party system which from there I fetch the default currency that should be displayed in my app. how can I somehow integrate both Vue I18 with third party API?

1

There are 1 best solutions below

0
Mohesn Mahmoudi On

Here's a simple example of how to achieve this, but if you have something more complex, you'll need to provide more information.

import { createApp } from 'vue';
import { createI18n } from 'vue-i18n';
import axios from 'axios';
import App from './App.vue';

const app = createApp(App);

// Create a VueI18n instance
const i18n = createI18n({
  legacy: false, // Use Composition API
  locale: 'en', // Set default locale
  fallbackLocale: 'en', // Fallback locale
  messages: {
    // Your localization messages
    en: {
      currency: '$' // Default currency symbol
    }
  }
});

// Fetch default currency from third-party API
axios.get('https://your-third-party-api.com/default-currency')
  .then(response => {
    const defaultCurrency = response.data.currency; // Assuming the API returns currency data
    // Update the currency symbol in the VueI18n instance
    i18n.global.locale.value.currency = defaultCurrency;
  })
  .catch(error => {
    console.error('Error fetching default currency:', error);
  });


app.use(i18n).mount('#app');