【问题标题】:How do i include a JSON file in VueJs without compiling it如何在不编译的情况下在 VueJs 中包含 JSON 文件
【发布时间】:2020-02-29 16:16:05
【问题描述】:

我正在尝试创建一个新的 VueJs 应用程序,但我遇到了各种各样的问题。我有一个大型 JSON 文件,其中包含一组对象,我根据搜索条件显示,但这会生成一个太大的 app.js 文件。启动应用程序的时间过长。

目前我将其导入为:

import SpellStore from '../store/spells.json'

这里是完整的组件:

<script>
import SpellBlock from '../components/SpellBlock.vue'
import SpellStore from '../store/spells.json'
export default {
    name: 'Spells',
    components: {
        SpellBlock
    },
    computed: {
        count: function () {
            return this.$store.state.count
        },
        spells: function () {
            var result = SpellStore
            if (this.filter.text) {
                result = result.filter(m => !m.name.toLowerCase().indexOf(this.filter.text.toLowerCase()))
            }
            return result;
        },

    },
    data(){
        return {
            maxResults: 50,
            filter: {
                text:'',
            },
          }
      }
};

问题: 当我为生产构建时,它会生成一个大约 12Mb 的 app.js 文件,只是因为 json 文件非常大。当我查看 app.js 的源代码时,我实际上可以在那里看到整个 json 对象。我的应用程序中没有太多其他内容。我不想在不需要这个大文件时给所有用户带来负担。如何仅在需要时加载此文件?我对谷歌也没有任何运气。我该如何处理?

已解决

async mounted() {
    await import("../store/spells.json")
        .then(({default: json}) => {
            this.SpellStore = json;
        });
    }

【问题讨论】:

  • 您可以将其作为静态文件,然后使用 xhr 加载。

标签: vue.js webpack


【解决方案1】:

我认为您可以通过 require import

实现这一目标
async mounted() {
  this.SpellStore = await import("../store/spells.json");
}

【讨论】:

  • 我试过了,但它并没有改变 myapp 文件的大小。它确实会加载文件
  • 啊,我明白了。您可以尝试改用import
  • 为了以后参考,我把它改成了这个:async mounted() { await import("../store/spells.json") .then(({default: json}) =&gt; { this.SpellStore = json; }); },
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
相关资源
最近更新 更多