How can I dynamically import a Vue instance?

Is there a way to dynamically import an instance in Vue while using a parameter?

I am interested in dynamic importing the language into flatpickr-vue.

import { de } from 'flatpickr/dist/l10n/de.js';

How can I make the "locale" parameter part of the import path dynamic?

<akaunting-date
...
      :config="{
            ...
            locale: '{{ language()->getShortCode() }}',
        }"
...
></akaunting-date>

Original code link

<template>
    <base-input :label="title"
        :name="name"
        :class="[
            {'readonly': readonly},
            {'disabled': disabled},
            formClasses
        ]"
        :footer-error="formError"
        :prependIcon="icon"
        :readonly="readonly"
        :disabled="disabled"
        >
        <flat-picker slot-scope="{focus, blur}"
            @on-open="focus"
            @on-close="blur"
            :config="config"
            class="form-control datepicker"
            v-model="real_model"
            @input="change"
            :readonly="readonly"
            :disabled="disabled">
        </flat-picker>
    </base-input>
</template>

<script>
import flatPicker from "vue-flatpickr-component";
import "flatpickr/dist/flatpickr.css";
import { de } from 'flatpickr/dist/l10n/de.js';

export default {
    name: 'akaunting-date',

    components: {
        flatPicker
    },

    props: {
        title: {
            type: String,
            default: '',
            description: "Modal header title"
        },
        placeholder: {
            type: String,
            default: '',
            description: "Modal header title"
        },
        readonly: {
            type: Boolean,
            default: false,
            description: "Input readonly status"
        },
        disabled: {
            type: Boolean,
            default: false,
            description: "Input disabled status"
        },
        formClasses: null,
        formError: null,
        name: null,
        value: {
            default: null,
            description: "Input value defalut"
        },
        model: {
            default: null,
            description: "Input model defalut"
        },
        config: null,
        icon: {
            type: String,
            description: "Prepend icon (left)"
        }
    },

    data() {
        return {
            real_model: this.model
        }
    },

    mounted() {
        this.real_model = this.value;

        if (this.model) {
            this.real_model = this.model;
        }

        this.$emit('interface', this.real_model);
    },

    methods: {
        change() {
            this.$emit('interface', this.real_model);
            
            this.$emit('change', this.real_model);
        }
    }
}
</script>

Link to original code

I feel like I'm making progress...

    computed: {
            config() {
                return {                
                    locale: require('flatpickr/dist/l10n/' + this.locale + '.js').default.en,
                }
            }
        },

Now I need to make the ".en" in .default change dynamically. Is that possible?

It's not completely dynamic yet and there's still the error message below that I don't quite understand

[Vue warn]: The computed property "config" is already defined as a prop.

Answer №1

Importing a module that is unknown at runtime requires asynchronous loading to prevent delays in script execution.

If you prefer not to use the promise.then() method, an alternative approach can be considered:

// Perform actions with the 'locale module' once it becomes available
function greetUserInLocale(locale, name) {
  console.log(locale.greeting + ' ' + name)
}

// Load the module asynchronously
async function loadLocale(countryCode, actionAfterLoad, ...additionalArgs) =>{
  const locale = await import(`localModules/${countryCode}.js`)
  actionAfterLoad(locale, ...additionalArgs)
})

loadLocale('FR', greetUserInLocale, 'Emily') // Executes asynchronously


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

Display the message "currently being loaded" on a Django platform

I'm a newcomer to django and styling and I have two things I want to address. First, I have an algorithm running on the upload file that takes time to load. I want to display a loading message until the output.csv file is generated and ready for downl ...

Is it more effective to pre-load all products and conduct searches solely within the front-end for an autocomplete search feature with previews?

Currently, I am developing a search feature using Laravel and Vue. The idea is to display product thumbnails in a panel as users type in their search query. Each letter input triggers an asynchronous update of the list. Now, I'm contemplating whether ...

Dynamic resizing navigation with JQUERY

I have successfully created a navigation menu that dynamically resizes each list item to fit the entire width of the menu using JavaScript. $(function() { changeWidth(500); function changeWidth(menuWidth){ var menuItems = $('#menu l ...

Identifying the selection of radio buttons using jQuery

Creating a form with radio buttons presents the challenge of detecting if all radios have been selected. To achieve this, I can use the simple function .change. In my case: $('input:radio').change(function() { alert($('[name|="pyt1 ...

Doing server side function calls from the client in NodeJs

I recently embarked on a journey to learn web development and am eager to make server-side data changes when invoking client functions. Take a look at my sample server setup: const fs = require('fs'); const path = require('path'); con ...

When attempting to fetch data from Strapi v4 and display it in ReactJS, all that is shown is an empty array

I've encountered an issue while trying to map data from Strapi, as I'm getting an empty array. Surprisingly, the endpoint functions properly when tested on Postman: https://i.sstatic.net/4B4O7.png The custom useFetch function seems to be malfunc ...

What is the best way to display values from a Localstorage array in a tabular format using a looping structure

I have set up a local storage key 'fsubs' to store form submissions as an array. Here is how I am doing it: var fsubs = JSON.parse(localStorage.getItem('fsubs') || "[]"); var fcodes = {"barcodeno" : this.form.value.barcode, "reelno" : ...

What is the method to prolong the end date of fullCalendar.js through Javascript?

I am facing the same issue as this individual. I am unsure of how to add one day to the end date. I do not want to alter the database value, only modify it on the HTML page. Currently, this is my calendar (no Moment.js joke intended): $(document).ready(f ...

Exploring nested object values in React Js through iteration

I have been searching extensively for a solution to no avail. I have an object created from fetched data with the following structure: { id: string, title: string, price: { currency: string, amount: number, }, ...

JavaScript's Ajax POST request to PHP is not functioning as expected

My current code setup involves handling $_GET[] requests on the products.php page by passing them to get_data_products.php via an ajax POST request. The data retrieved from get_data_products.php is then displayed accordingly. PHP if(isset($_GET['cat ...

Assistance needed in retrieving an element using jQuery

After posting a similar question and receiving a correct answer that didn't quite meet my needs, I realized it was my mistake. Imagine having the following HTML: <TD nowrap="true" valign="top" width="190px" class="ms-formlabel"> <H3 class=" ...

What distinguishes the sequence of events when delivering a result versus providing a promise in the .then method?

I've been diving into the world of Promises and I have a question about an example I found on MDN Web Docs which I modified. The original code was a bit surprising, but after some thought, I believe I understood why it behaved that way. The specific ...

Deactivate a function when the dropdown input is selected

I'm currently using a function to attach scroll events to a slider element for navigating through slides. However, I want to temporarily disable this function in specific situations - such as when a dropdown is in focus - to allow smooth scrolling thr ...

What is the process for importing css and js files in laravel-webpack when utilizing a newly installed package through composer?

I've been working on installing this package called phackage. You can find more information about it here. After successfully installing it with Composer PHP, I've encountered several errors because I'm using Laravel 5.4 with Webpack 2 and ...

The flow of Node.js persists despite a response being dispatched

The code snippet I have below checks for spaces in a text, verifies a link asynchronously, and handles post requests. However, there is an issue when the email and password fields are null, resulting in an error message "Cannot read property 'trim&apo ...

I am looking to incorporate a new "ID" column into my mui data grid table in ReactJS that will incrementally count from 0 to the total number of rows

When displaying data from an API in a datagrid table component with multiple columns, it is necessary to include a column for the ID which should have values ranging from 0 to the number of rows. Currently, the Object_id is being displayed in this cell. T ...

Is it possible to invoke the same function twice on HTML5 Canvas?

I'm feeling overwhelmed as a beginner with HTML 5 canvas. I'm struggling with this particular function: function drawcircle(x,y) { context.save(); context.strokeStyle = '#00ff00'; context.fillStyle = '#000000'; ...

triggering Javascript upon page load

Looking to execute my Javascript only once during page load, and not during postbacks. Using Asp.net 3.5. ...

Troubleshooting: Why Isn't Calling a PHP Function from AJAX Working

I'm attempting to utilize AJAX to call a PHP function. Here's the script I've implemented. <script type="text/javascript" src="jquery.1.4.2.js"> $(document).ready(function () { // after EDIT according to ...

Utilize Redux in conjunction with TypeScript to seamlessly incorporate a logout feature

My login page redirects to a private /panel page upon successful login with an accessToken. I am utilizing the Redux store to verify the token in the privateRoute component. Challenges I'm encountering: I aim to enable logout functionality from t ...