Getting external JSON data in a Vue.js app is a common requirement for dynamic web apps. There are two main cases:
- importing a local JSON file
- fetching JSON from an external server.
Here’s how to handle both:
Importing a Local JSON File
If your JSON file is part of your project (e.g., in the src/assets or src/json folder) you can import it directly into your component:
<script>import jsonData from ‘./json/data.json’;
export default {
data() {
return {
myJson: jsonData
};
}
};
</script>
<template>
<div>
<div v-for=”item in myJson” :key=”item.id”>
{{ item.name }} – {{ item.value }}
</div>
</div>
</template>
Fetching JSON Data from an External Server
To access a JSON file hosted on a server or API, use the fetch API or a library like Axios:
Using Fetch API
<script>export default {
data() {
return {
myJson: []
};
},
mounted() {
fetch(‘https://example.com/data.json’)
.then(response => response.json())
.then(data => {
this.myJson = data;
})
.catch(error => {
console.error(error);
});
}
};
</script>
<template>
<div>
<div v-for=”item in myJson” :key=”item.id”>
{{ item.name }} – {{ item.value }}
</div>
</div>
</template>
Also Read: Why Enterprises are Choosing Vue.js for their Large-Scale Projects?
Using Axios Library
<script>import axios from ‘axios’;
export default {
data() {
return {
myJson: []
};
},
mounted() {
axios.get(‘https://example.com/data.json’)
.then(response => {
this.myJson = response.data;
})
.catch(error => {
console.error(error);
});
}
};
</script>
Key Takeaway
- Use import for static, local JSON files.
- Use fetch or axios for external or dynamic JSON data.
- Always handle errors and ensure your data structure matches your code.