Skip to content Skip to sidebar Skip to footer

How To Load Data Into Vue.js From An External File Using Vue Only

in this vue example down below I'm trying to load the 'images' array from an external js file using vue only. I tried something similar to this post: How do I access data from an

Solution 1:

It really depends on what "external" means, and what "Vue only" means. If you have control over the data, it's structure and it's location, you can do something like what @softbear has done - just import a javascript file inside your project. You can do it in numerous ways depending on your setup. His example consists of

<scriptsrc="images.js"></script>

which exports something along the lines of

window.images = [{ 'array of images': 'goes here'}]

If you're using Vue you should be able to use the bootstrapped project and just import this from your source files directly.

You can have a backend that provides the same result, and the browser will automatically load it when importing the script.

There are numerous ways but the result is the same. The most important thing here is that this file must declare your variable that should be used later on.


There are few problems with the approach on top: you don't have full control of when to start loading the data, nor when the data is loaded (there are ways to do that, but harder and pretty ugly); some cross domain serves don't allow you to execute js code directly - they can only provide data.

Which means that if you end up in this situation (like connecting to a dynamic set of data and not a hardcoded one), it's always better to make a request to load this data. Basically manually doing what the browser can do for you. But this way you have full (and easy) control of when and how this is done.

Again there are numerous ways - if you're using latest JS in a modern browser you can use the fetch API, or use some external tools like axios.

I would vote for the second approach, despite it might add another dependency to your project.

Post a Comment for "How To Load Data Into Vue.js From An External File Using Vue Only"