简体   繁体   English

如何将服务器端 JSON 传递/导入到 vue 应用程序?

[英]How to pass/import server-side JSON to a vue app?

I'm building a webapp that requires a JSON file as data.我正在构建一个需要 JSON 文件作为数据的 webapp。 The person using my app in their website should be able to pass in a JSON file hosted on their server so that my app can read it.在他们的网站上使用我的应用程序的人应该能够传入托管在他们服务器上的 JSON 文件,以便我的应用程序可以读取它。

In development, I just used import mydata from "./mydata.json" , but this won't work in production.在开发中,我只是使用import mydata from "./mydata.json" ,但这在生产中不起作用。 I tried to have a computed property that returns require (this.publicPath + this.datapath) (where this.publicPath is process.env.BASE_URL , but it's not able to find the file (if it's relevant, I'm using vue-cli to build).我试图有一个返回require (this.publicPath + this.datapath)的计算属性(其中this.publicPathprocess.env.BASE_URL ,但它无法找到该文件(如果它相关,我正在使用 vue- cli来构建)。

The structure of my app is that I have a wrapper App.vue and then the main component, main-component.vue (so that I can pass a prop containing data to the main component).我的应用程序的结构是我有一个包装器App.vue ,然后是主组件main-component.vue (这样我就可以将包含数据的道具传递给主组件)。

What's the best way to do this?最好的方法是什么? I've tried using a <script> tag in index.html , but apparently that's not supported with JSON.我尝试在index.html中使用<script>标记,但显然 JSON不支持该标记。 I don't want to use other libraries like jQuery.我不想使用 jQuery 等其他库。

(I'm thinking that I could have the user just import their file with the ES6 syntax by creating a new Vue component/app, but I'm not sure how to do that in pure HTML). (我想我可以让用户通过创建一个新的 Vue 组件/应用程序来使用 ES6 语法导入他们的文件,但我不确定如何在纯 HTML 中做到这一点)。

If you can try using a.js file that migh work and you can structure the data the same way as in a.json file, afterall a json is just a js object, also i had this problem while doing the same thing.如果您可以尝试使用可能有效的 a.js 文件,并且您可以像在 a.json 文件中一样构造数据,毕竟 json 只是一个 js object,我也遇到了这个问题。 DISCLAIMER: you might have to restructure your data to be in an exported variable if that is possible, like so:免责声明:如果可能的话,您可能必须将数据重组为导出变量,如下所示:

export const myObj = {your json}导出 const myObj = {你的 json}

As an extension of my comment: what you're looking for is to actually fetch the JSON from your server using an XMLHttpRequest.作为我评论的延伸:您正在寻找的是使用 XMLHttpRequest 从您的服务器实际获取 JSON。 You can do this in a modern, ES6-manner using the Fetch API :您可以使用Fetch API以现代 ES6 方式执行此操作:

fetch('/path/to/your/json')
  .then(resp => resp.json())
  .then(data => {
    // Access the parsed JSON as `data`
    console.log(data);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM