【问题标题】:is there a way to get a json file once and use it anywhere in vue3 like global variables?有没有办法一次获取一个 json 文件并在 vue3 中的任何地方使用它,比如全局变量?
【发布时间】:2022-01-10 17:59:11
【问题描述】:

我一直在寻找一种方法,可以在组件中获取一个 json 文件,然后在同一个组件和其他组件上使用它,就像使用全局变量一样。

我看过this (它会在我在模板中使用它之后设置变量,所以它会在控制台中显示未分配的变量错误) 但它不起作用 而且我还查看了 vue3 文档,但没有找到任何可行的方法。

所以我什么也没找到,只能在每个组件中发送请求。

showHome.vue:

<script>
import axios from 'axios';
export default {
  created(){
    axios.get("http://api.mjbn.ir/post")
  .then((response) => {
    this.getposts = response.data;
    });
  },
  data: function () {
    return {
      postsearch: "",
      post: true,
      product: true,
      getposts: this.getposts,
    };
  },
  methods: {
    showReq(input0, input1) {
      this.post = input0;
      this.product = input1;
    },
    btnActive(input0) {
      if ((input0 == "post") & (this.post == true) & (this.product == false)) {
        return true;
      } else if ((input0 == "product") & (this.product == true) & (this.post == false)) {
        return true;
      } else if ((input0 == "all") & (this.post == true) & (this.product == true)){
        return true;
      } else {
        return false;
      }
    },
    showRes(input0) {
      if ((input0 == "post") & (this.post == true)) {
        return true;
      } else if ((input0 == "product") & (this.product == true)) {
        return true;
      } else if ((input0 == "all") & (this.post == true) & (this.product == true)){
        return true;
      } else {
        return false;
      }
    },
    postCount(){
      const posts = this.getposts
      let count = 0;
      if (this.post == true & this.product == true){
        return this.getposts.length;
      } else if (this.post == true & this.product == false){
        for (let index = 0; index < posts.length; index++) {
          const element = posts[index];
          if (element.type == 'post') {
            count++;            
          }
        }
        return count;
      } else if (this.post == false & this.product == true){
        for (let index = 0; index < posts.length; index++) {
          const element = posts[index];
          if (element.type == 'product') {
            count++;            
          }        
        }
        return count;
      }
      return "...";
    },
  },
};
</script>
<template>
        <div class="col-12 mt-5">
          <div class="row">
            <div v-for="getpost in getposts" v-show="showRes(getpost.type)" :key="getpost.id" class="col-4">
              <router-link :to="{ name: 'post', params: { id: getpost.id } }">
                <div class="col-6 mx-auto align-self-center">
                  <img
                    :src="getpost.img"
                    :alt="getpost.title"
                    class="img-fluid img-thumbnail"
                  />
                  <h5 class="text-center my-3">{{ getpost.title }}</h5>
                </div>
              </router-link>
            </div>
          </div>
        </div>
</template>

showPosts.vue:

<template>
  <!-- Post -->
  <div v-for="getpost in getposts" v-show="getpost.type == link" :key="getpost.id" class="col-8 my-3 mx-auto blog-post">
    <router-link
      :to="{ name: link, params: { id: getpost.id } }"
      style="color: #f8f8f2"
    >
      <div class="col-2 float-start">
        <img
          :src="getpost.img"
          :alt="getpost.title"
          class="img-fluid img-thumbnail"
        />
      </div>

      <div class="col-10 float-end">
        <div class="col-10 ms-4 me-4">
          <h2>{{ getpost.title }}</h2>

          <figure class="figure figure-caption">{{ getpost.date }}</figure>
        </div>

        <div class="col-10 ms-4 me-4">
          <p>{{ getpost.summerry }}</p>
        </div>
      </div>
    </router-link>
  </div>
</template>
<script>
import axios from 'axios';
export default {
  created() {
    axios.get('http://api.mjbn.ir/post')
    .then(response => { this.getposts =  response.data})
  },
  data: function () {
    return {
      getposts: this.getposts,
      link: "post",
    };
  },
};
</script>

main.js:

import "./assets/css/bootstrap.rtl.min.css";
import "./assets/css/main.css";
import { createApp } from "vue";
import { createWebHashHistory, createRouter } from "vue-router";
import showAbout from "./components/showAbout.vue";
import showBlog from "./components/showBlog.vue";
import showHome from "./components/showHome.vue";
import showLoading from "./components/showLoading.vue";
import showPage from "./components/showPage.vue";
import showHeader from "./components/showHeader.vue";
import showPost from "./components/showPost.vue";
import showPosts from "./components/showPosts.vue";
import showContact from "./components/showContact.vue";

// Routes
const routes = [
  {
    path: "/",
    component: showHeader,
    children: [
      { path: "", component: showHome,},
      { path: "/contact", component: showContact },
      { path: "/about", component: showAbout },
    ],
  },
  {
    path: "/blog",
    component: showBlog,
    children: [
      { path: "", component: showPosts },
      { path: "/blog/:id", name: "post", component: showPost },
    ],
  },
  { path: "/loading", component: showLoading },
];

// Router
const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
});

// App
const app = createApp(showPage);
app.use(router);
app.mount("#app");

【问题讨论】:

  • 将其加载到您的主应用程序组件中,然后将其传递给任何需要它的子组件。 v3.vuejs.org/guide/component-props.html#passing-an-array
  • 或者把它放在你的 Vuex 商店里。
  • 这是全局状态的用途,通常是 Vuex。
  • @ChrisG 那么我应该在根组件中获取文件并将其传递给每个子组件,如果我将来有一个大的 json 文件会增加加载时间
  • @EstusFlask 我不知道 vuex,但我会尝试,我认为它会工作

标签: javascript vue.js vue-router vuejs3


【解决方案1】:

感谢 cmets 中的 connexoestus flask。我知道有一个叫做vuex 的东西会为你工作。 这是语法。

main.js:

import { createApp } from "vue";
import { createStore } from "vuex";
import showPage from "./components/showPage.vue";

// Store
const store = createStore({
  state() {
    return {
      getjson: null,
    };
  },
  mutations: {
    getfile(state) {
      axios
        .get("https://jsonplaceholder.typicode.com/todos/1")
        .then((response) => {
          if (state.getjson == null) {
            state.getjson = response.data;
          }
        });
    },
  },
});

// App
const app = createApp(showPage);
app.use(store);
app.mount("#app");

在组件中:

<template>
<!-- run setposts before using getjson -->
  {{this.setposts()}}
  {{this.$store.state.getjson}}
</template>
<script>
export default {
  methods:{
    setposts(){
      this.$store.commit("getfile");
    }
  }
};
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 2020-12-08
    • 2021-04-14
    • 2022-10-04
    • 2016-05-23
    • 2019-05-27
    相关资源
    最近更新 更多