user3707042
user3707042

Reputation: 85

Vue3: Using dynamically imported JSON in template

In my Vue3 view, I need to import json using dynamic path, since the json filename depends on browser url. For example domain.com/canada uses ..canada.j́son and domain.com/use uses ..usa.json while in both cases same view file is used.

I have managed to import the json and can play with it inside the import function just fine. But how on earth do I get the json out of the import function so that I could use it in the template? See the comments inside the code below. This is views/test.vue

   <template>
        <div class="card">
            <h1>{{ IWantContentFromJsonHere }}</h1>
        </div>
    </template>
    
    <script>
    import { computed } from "vue";
    import { useRoute } from "vue-router";
    
    export default {
        name: "Test",

        //Value for this is coming from router/index.js
        props: ["jsonLocation"], 

        //Here I tried to set a variable outside the import scope
        //but it is not working. See comments below
        let var1 = "original value"; 
        
        setup(props) {
            import(`@/assets/json/${props.jsonLocation}`).then((module) => {
                //this below are working just fine, so json is parsed OK.
                console.log(module.default.canada.toronto);
                
                
                //this prints "original value" so var1 works here
                console.log(var1);
                //and I can change the value of var1 here to print the json
                var1 = module.default
                console.log(var1); //this prints the json
            });
            return {
                //and i can return the var1 here, but the value here is "original value"
                //So if I use it at template at top of the code, 
                //it just renders "original value", not the json I want
                var1

            };
        },
    };
    </script>
    <style scoped lang="scss">
    </style>

Upvotes: 6

Views: 4788

Answers (1)

akuiper
akuiper

Reputation: 214957

You need to define your variable as a Ref in order to make the variable reactive, i.e. dom gets updated when var1 gets updated:

import { ref } from 'vue'
    
setup(props) {
    let var1 = ref("original value"); 

    import(`@/assets/json/${props.jsonLocation}`).then((module) => {
        var1.value = module.default // modify var1 by assigning to var1.value
    });
    return {
        var1
    };
},

Upvotes: 8

Related Questions