Vue3: Using dynamically imported JSON in template
Asked Answered
L

1

6

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>
Lewie answered 8/2, 2021 at 21:44 Comment(0)
R
8

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
    };
},
Rework answered 8/2, 2021 at 22:9 Comment(1)
note if you're using Vue 2 you can call the same import() method in created or watch for a similar outcomeDryer

© 2022 - 2024 — McMap. All rights reserved.