How to access external json file objects in vue.js app
Just assign the import to a data property
<script>
import json from './json/data.json'
export default{
data(){
return{
myJson: json
}
}
}
</script>
then loop through the myJson
property in your template using v-for
<template>
<div>
<div v-for="data in myJson">{{data}}</div>
</div>
</template>
NOTE
If the object you want to import is static i.e does not change then assigning it to a data property would make no sense as it does not need to be reactive.
Vue converts all the properties in the data
option to getters/setters for the properties to be reactive. So it would be unnecessary and overhead for vue to setup getters/setters for data which is not going to change. See Reactivity in depth.
So you can create a custom option as follows:
<script>
import MY_JSON from './json/data.json'
export default{
//custom option named myJson
myJson: MY_JSON
}
</script>
then loop through the custom option in your template using $options
:
<template>
<div>
<div v-for="data in $options.myJson">{{data}}</div>
</div>
</template>
Read and display JSON data from external file in Vue.JS
there are multiple solution but as i believe you are very new to Vue JS and learning Vue i will keep things simple.
Add a file data.json
{
"messages": [
{
"name": "AI",
"message": "Hello Doctor"
},
{
"name": "Shri",
"message": "Hello there!"
},
{
"name": "AI",
"message": "Hope you are well. Today's discussion shall be on treatment options to manage ..."
}
]
}
update your Js file as
const app = new Vue({
el: "#app",
data: {
messages: []
},
methods: {
loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', './data.json', true)
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
},
init() {
let that = this
that.loadJSON(function (response) {
// Parse JSON string into object
var data = JSON.parse(response);
that.messages = data.messages
});
}
},
mounted(){
this.init()
},
template: `
<div>
<p v-for="message in messages"><b>Name: </b>{{message.name}} </br><b>Message: </b>{{message.message}}</br></p>
</div>
`
})
loadJSON is just a basic HHTP request and load the data from json file. inside init call back you can set data to local instant
Import data from a JSON file in Vue.js instead of manual data
Vue cli:
set that data inside a file called posts.json
and import it as follows :
import posts from "./posts.json";
and assign it to your postList
in the mounted
hook :
computed:{
....
},
mounted(){
this.postList=posts
}
CDN
in your case you should use an AJAX api like axios
computed:{
....
},
mounted(){
axios
.get('posts.json')
.then(response => (this.postList = response.data))
}
}
and your should include the following scripts :
<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue-axios@2.1.4/dist/vue-axios.min.js"></script>
Full example
var app = new Vue({ el: '#app', data: { keyword: '', postList: [] }, computed: { filteredList() { return this.postList.filter((post) => { return post.title.toLowerCase().includes(this.keyword.toLowerCase()); }); } }, mounted(){ axios.get('https://jsonplaceholder.typicode.com/posts') .then((response)=> { this.postList=response.data; }) }});
<html lang="en" dir="ltr">
<head> <meta charset="utf-8"> <title></title> <script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <script src="https://unpkg.com/vue-axios@2.1.4/dist/vue-axios.min.js"></script></head>
<body> <div id="app">
<div class="wrapper">
<table style="width:100%; text-align: left;"> <tr> <th style="text-align: left; width: 33%">ID</th> <th style="text-align: left; width: 33%">Title</th> <th style="text-align: left; width: 33%">Body</th> </tr> </table>
<div v-for="post in postList"> <table style="width:100%; text-align: left"> <tr style="text-align: left;"> <td style="text-align: left; width: 33%">{{ post.id }}</td> <td style="text-align: left; width: 33%">{{ post.title}}</td> <td style="text-align: left; width: 33%">{{ post.body }}</td> </tr> </table> </div>
</div> </div></body>
how to get data from JSON file in Vue.js?
You can use a computed property that would reactively take account_name
property of the first object of every array:
const data = {
"data": [
[
{
"account_id": "11",
"account_name": "name11"
},
{
"account_id": "12",
"account_name": "name12"
},
{
"account_id": "13",
"account_name": "name13"
},
{
"account_id": "14",
"account_name": "name14"
}
],
[
{
"account_id": "21",
"account_name": "name21"
},
{
"account_id": "22",
"account_name": "name22"
},
{
"account_id": "23",
"account_name": "name23"
}
],
[
{
"account_id": "31",
"account_name": "name31"
},
{
"account_id": "32",
"account_name": "name32"
},
{
"account_id": "33",
"account_name": "name33"
}
]
]
}
new Vue({
el: '#demo',
data() {
return {
data: data.data
}
},
computed: {
firstAccountNames() {
return this.data.map(dataSet => dataSet[0].account_name)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<ul>
<li v-for="name in firstAccountNames">
{{ name }}
</li>
</ul>
</div>
How do I access data from an external file in Vue.js?
When you import any file, webpack uses an appropriate loader
(specified in your webpack.config.js
) to build the file. In case it is a .vue
file, it uses vue-loader
to build the file and return a Vue component. You need an Array containing your data, not a vue component. You can import simple .js
and .json
files for this.
Instead of importing a .vue
file. you can just import .json
or .js
file.
data.js
const data = [{ log1d: 1, logDetail: 'This is some log detail for log 1', logType: 'general', createdBy: 'name', CreatedAt: 'date' },
{ log1d: 2, logDetail: 'This is some log detail for log 2', logType: 'general', createdBy: 'name2', CreatedAt: 'date2' },
{ log1d: 3, logDetail: 'This is some log detail for log 3', logType: 'general', createdBy: 'name3', CreatedAt: 'date3' },
{ log1d: 4, logDetail: 'This is some log detail for log 4', logType: 'general', createdBy: 'name4', CreatedAt: 'date4' }
]
export default data;
component.vue
import logs from 'data.js'
export default {
data () {
return {
logitems: logs
}
}
}
Related Topics
Prevent a White Space in the Beginning of a Input
How Get Total Sum from Input Box Values Using JavaScript
How to Download Pdf Automatically Using Js
Javascript: Location.Href to Open in New Window/Tab
Show Base64 Pdf Data Using Window.Open on Chrome New Version
How to Style HTML Select Option Hover and Selected Option Effects
To Get a Popup Message After Submit
Fetch() Unexpected End of Input
Print Pdf Directly from JavaScript
Vue.Js Add Objects to Existing Array
Call a Function from an If-Statement Inside a Function
Regular Expression to Check Only One Decimal Point
How to Change Colour of Text Based on Its Value When a Page Initially Loads
How to Cancel Ongoing Http Requests When There's a New Requests in Angular 6 With Rxjs 6
How to Replace Double/Multiple Slash to Single in Url
Force Download a Pdf Link Using Javascript/Ajax/Jquery