Accessing JSON objects Vue.js
We need to access json files objects most of the time when we work on a project that use JSON to pass
data. If you want to access an external JSON file object in Vue.js what will you do?. First step is to load
the JSON file.
import json from './json/data.json'
Assign the import to a data property.
<script>
import json from './json/data.json'
export default{
data(){
return{
myJson: json
}
}
}
</script>
Now use v-for and loop through myjson property in your template.
<template>
<div>
<div v-for="data in myJson">{{data}}</div>
</div>
</template>
If the object you want to import is static then it would make no sense if you assign it to data property. It is
because vue converts all the properties in the data option to setter/getters for the properties to be
reactive.So create a custom option:
<script>
import MY_JSON from './json/data.json'
export default{
//custom option named myJson
myJson: MY_JSON
}
</script>
Then loop it using $options.
<template>
<div>
<div v-for="data in $options.myJson">{{data}}</div>
</div>
</template>
Comments
0 comments
Please Sign in or Create an account to Post Comments