【发布时间】:2021-05-11 08:14:18
【问题描述】:
我正在尝试做一个简单的单页网站,其文本存储在本地 json 文件中。假设它是一个网站,在不同的视图(页面)上列出了著名的卡通猫和狗。猫和狗的视图模板 (views/testcard.vue) 是相同的,但猫和狗的文本存储在单独的 json 文件中 (assets/json/cats.json & assets/json/dogs.json)。
我知道如何将 json 导入视图,但那是静态路径。但问题是:如何使用基于 props/params 的路径将 json 导入视图,以便在猫的情况下为cats.json,在狗的情况下为dogs.json?
网址格式为 domain.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 没有什么不同。该网站不会对外部资源进行任何调用,因此我希望尽可能简单。
【问题讨论】:
标签: javascript vue.js webpack vue-cli vuejs3