在 Vue3 中使用动态路径加载本地 json

Loading local json using dynamic path in Vue3

我正在尝试创建一个简单的单页网站,该网站的文本存储在本地 json 文件中。假设这是一个在单独的视图(页面)上分别列出著名卡通猫和狗的网站。猫和狗的视图模板 (views/testcard.vue) 是相同的,但是猫和狗的文本存储在单独的 json 文件中 (assets/json/cats.json & assets/json/dogs.json).

我知道如何将 json 导入视图,但那是静态路径。但问题是:如何使用基于 props/params 的路径将 json 导入视图,以便在猫的情况下它是 cats.json 而在狗的情况下它是 dogs.json?

网址以域的形式出现。com/cat/garfield我通过以下方式成功地在视图文件中提供了物种(猫/狗)和个体动物(加菲猫,冥王星......)路由器 (router/index.js) 如下所示。

{
        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",
        },
    },

而 views/Testcard.vue 看起来像这样:

<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>

我正在使用 Vue3,但这可能与 Vue2 没有什么不同。该网站不会对外部来源进行任何调用,因此我希望尽可能简单。

不要在 json 中存储 @ 别名,否则 Webpack 将无法找到该文件。可以去掉整个路径:

jsonLocation: "cats.json"
jsonLocation: "dogs.json"

当您动态使用 import 时,它 returns 一个承诺,它解析为 default 属性 中带有 json 的模块:

setup(props) {
  import(`@/assets/json/${props.jsonLocation}`).then(module => {
    console.log(module.default);
  });
},