I am trying to do a simple single page website that has texts stored in a local json files. Let's say it is a website that lists famous cartoon cats and dogs each on separate view (page). The view template (views/testcard.vue) for both cats and dogs is the same, but texts for cats and dogs are stored in separate json files (assets/json/cats.json & assets/json/dogs.json).
I know how to import a json to the view, but that is a static path. But the QUESTION IS: How do I import the json to the view using path that is based on props/params so that in case of a cat it is cats.json and in case of a dog it is dogs.json?
The urls are in form of domain.com/cat/garfield I have succesfully made both the specie (cat / dog) and individual animal (Garfield, Pluto...) available in the view file by providing them via router (router/index.js) like shown below.
{
path: "/cats/:currentAnimal",
name: "Cats",
component: () => import("../views/Testcard.vue"),
props: {
currentType: "cat",
jsonLocation: "@/assets/json/cats.json",
},
},
{
path: "/dogs/:currentAnimal",
name: "Dogs",
component: () => import("../views/Testcard.vue"),
props: {
currentType: "dog",
jsonLocation: "@/assets/json/dogs.json",
},
},
And views/Testcard.vue looks like this:
<template>
<div class="card">
<h1>{{ currentAnimal }} is a famous {{ currentType }}</h1>
</div>
</template>
<script>
import { computed } from "vue";
import { useRoute } from "vue-router";
//the line below would work, but it is static path
//import json from '@/assets/json/cats.json';
export default {
name: "Testcard",
props: ["currentType", "jsonLocation"],
setup() {
const route = useRoute();
const currentAnimal = computed(() => route.params.currentAnimal);
return {
currentAnimal,
};
},
};
</script>
I am using Vue3, but this might not be any different from Vue2. The website will not have any calls to outside sources so I would like to keep this as simple as possible.