使来自 App.vue 的 JSON 数据可在所有视图中访问 [英] Make JSON data from App.vue accessible in all views

查看:28
本文介绍了使来自 App.vue 的 JSON 数据可在所有视图中访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我的 Vue3 SSA 包含以下文件:
App.vue
浏览次数/首页
浏览次数/Page_A
浏览次数/Page_B

My Vue3 SSA so far consists of the following files:
App.vue
views/Home
views/Page_A
views/Page_B

在 App.vue 中,JSON 文件通过 API 加载.主页和A页和B页都需要数据.
使用下面的代码,我从 API 加载数据,如果在每个视图文件中单独完成,我可以在相应的模板中使用它.

In App.vue a JSON file is loaded via an API. The data is needed on the home page and on pages A and B.
With the following code, I load the data from the API and if it is done in each view file separately, I can use it in the corresponding template.

<script>
import axios from "axios";

export default {
    name: "RenderList",
    props: {
        msg: String,
    },
    data() {
        return {
            listDataString: String,
            listData: [], // placeholder
        };
    },
    mounted() {
        axios
            .get('https://www.dev.domain.de/wp/wp7/all_json/?maxCounts=20&order=DESC')
            .then((response) => {
                this.listDataString = JSON.stringify(response.data, null, "\t");
                this.listData = response.data;
                console.log(this.listData);
                return response; // multiline arrow function must return
            });
    },
};
</script>

但是由于 API 数据不会改变,所以在 App.vue 中加载一次就足够了,然后将其提供给视图文件.

But since the API data does not change, it would be enough to load it once in the App.vue and then make it available to the view files.

分发数据的正确程序是什么?
我刚刚找到了一种存储在 localStorage 中的方法,但这种方式可能会被用户禁用.也许我只需要一个提示而不需要代码,这样我就能找到自己.

What is the correct procedure to distribute the data?
I just found a way to store in localStorage, but this way could be disabled by the user. Maybe i just need a hint and no code, so i can find out myself.

推荐答案

非常感谢您的评论@Ohgodwhy

Thank you very much for your comment @Ohgodwhy

所以我的解决方案比我想象的要容易得多.
这在每个 view.vue 中都可用:

So my solution is much easier than i thought.
This is usable in every view.vue:

<table id="items">
    <tr v-for="(item, index) in this.$root.listData" :key="index">
        <td class="p-1">{{ item.name }}</td>
        <td class="p-1">{{ item.city }}</td>
        <td class="p-1">{{ item.country }}</td> 
    </tr>
</table>

这篇关于使来自 App.vue 的 JSON 数据可在所有视图中访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆