Sometimes we need to read our application basic settings but from an external file rather than having everything hardcoded so that some endpoints and settings can change through time even if you are in production mode, we can make a get method with Axios to get information of a given .json file locally, in my case I called it data.json which is going to be at the same level of index.html, that .json file as you want to name it can change its values as you need through time, after we compiled the project the structure would be something like this and keep in mind, inside the folder dist is where are going to be the .js files, images, and other needed files by the app.
|-index.html
|-data.json
|--dist
we must install Axios with npm install --save axios, I created a Vue empty project and a .json file called data.json
{
"movies": [ { "title": "The Boy", "watched": false }, { "title": "Avengers: Age of Ultron", "watched": true }, { "title": "Avengers Assemble", "watched": true }, { "title": "Scott Pilgrim", "watched": true }, { "title": "Tron: Legacy", "watched": true }, { "title": "The Hunger Games: Mockingjay Part 2", "watched": false } ] } |
and I just can call that local data.json file anywhere like this:
we first make the Axios import
import axios from 'axios';
|
and you can get it anywhere with:
axios.get('/datas.json')
.then((response)=> {
console.log(response.data.movies);
})
|
this the App.vue
<template>
<div id="app">
<img src="./assets/logo.png">
<h1>{{ msg }}</h1>
<ul>
<li v-for="(movie,index) in movies" :key="index">
<p>Title: {{movie.title}}</p>
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'app',
data () {
return {
msg: 'Welcome to Your Vue.js App',
movies:''
}
},
beforeCreate() {
axios.get('/datas.json')
.then((response)=> {
this.movies = response.data.movies;
console.log(response.data.movies);
})
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
h1, h2 {
font-weight: normal;
}
li {
display:inline;
}
a {
color: #42b983;
}
</style>
|
after running npm run build you get something like this, now you just edit your file data.json reload and you'll get the chances rebuilding again.
Comments
Post a Comment