How to access external json file objects in vue.js application

How to access JSON objects in vue.js application I am new to this

import json from './json/data.json' 

the JSON file is loading, and now I need to access the objects inside it

+5
source share
2 answers

Just assign the data property to the import

 <script> import json from './json/data.json' export default{ data(){ return{ myJson: json } } } </script> 

then swipe 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, that is, it does not change, and assigning it to the data properties does not make sense, since it should not be reactive.

Vue converts all the properties in the data option to getters / setters so that the properties are reactive. Thus, it would not be necessary for vue to set getters / seters for data that will not change. See Jet 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 scroll through the custom option in your template using $options :

 <template> <div> <div v-for="data in $options.myJson">{{data}}</div> </div> </template> 
+10
source

If your file looks like this:

 [ { "firstname": "toto", "lastname": "titi" }, { "firstname": "toto2", "lastname": "titi2" }, ] 

You can do:

 import json from './json/data.json'; // .... json.forEach(x => { console.log(x.firstname, x.lastname); }); 
+3
source

Source: https://habr.com/ru/post/1270675/


All Articles