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>
import()
method increated
orwatch
for a similar outcome – Dryer