简体   繁体   中英

Vue load a JS file with a javascript object in a runtime

I am building a no-code application using Vue. I have an idea that I have some JSON file and import it on runtime. However, JSON file don't allow to add a function. I change to use a javascript or typescript file to store the JSON object like below.

export {
  "is": "button",
  "props": {
    "type": "button"
  },
  "events": {
    "click": () => {
      // do something
    }
  }
}

Currently, I want to trigger the import when Vue created the component.

{
  created () {
    // import here
  }
}

I have two methods that I have tried:

  1. Add a script tag but I need something to store it first, like window
  2. use import but it only supports local file.

I store these files in backend and load each of them when frontend need it. Is there any better solution? Please help and thank you.

It sounds like you essentially want to do something like deferred module loading, if you use Webpack you may want to have a look at this: https://alexjover.com/blog/lazy-load-in-vue-using-webpack-s-code-splitting/

I'm not sure I can recommend the approach that you're taking but if you do want to stick with it, your solution would probably look something like:

  1. Make an HTTP get request to the URL of your file. This should be a plain text response, not JSON. The file itself can be a .js file containing an object literal ( { a: ..., b: ..., c: ... } ) with function definitions.
  2. Once you get the text, evaluate it with eval(...the response) and save it to a local variable which you can then use. Note that if the code in your file has any dependencies, you will have to come up with some way to bring those over as well.

Clearly though, this is a lot of trouble and probably not worth it. Code splitting in general is only worth the effort if it's a fairly big app; for smaller apps the cost of the round trips outweighs the cost of loading the initial bundle.

In any case, you'll likely have more luck using Vue's baked-in dynamic import system than a hand-rolled solution, but it really just depends on what you're trying to achieve here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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