[Vuejs]-How to call an imported module by using a string variable for it's name in JavaScript and VueJS

2👍

Thanks to @Bergi suggestion in the comments I was able to call modules dynamically using string variable. The solution was to create an object in my component data where its properties were named the same as the modules and their values were references to the modules themselves. Please see the code example below.

<template>
     //Some code here that call for the function "myFunction" and pass to it an object...
</template>

<script>
    import Task from "../../APIs/Task"
    import Status from "../../APIs/Status"
    
    export default{
        data(){
            return {
                modules:{
                    Task: Task,
                    Status: Status
                }
            }
        },
        methods: {
            myFunction(someObject){
            !-- This works! -->
              this.modules[someObject.moduleNameAsStoredOnObject].someFunctionThatBothModulesHave(someObject.payload)
            }
        }
    }
</script>

0👍

At a glance, should the brackets be around just the module name?

someObject[moduleNameAsStoredOnObject].someFunctionThatBothModulesHave(someObject.payload)

The way you have it, [someObject.moduleNameAsStoredOnObject] is an array containing the module name. So you’re trying to call someFunctionThatBothModulesHave on an array.

Leave a comment