Part 4: HTTP
Step 1: Load data on mounting
- Implement the
mounted()
method and fill data with the JSON file (as before). Mounted function looks like this:
export default {
name: 'MyComponent',
data () {
return {
awesomeDatas: []
}
},
mounted () {
console.log('Hey, I just get mounted!')
this.awesomeDatas = ['bim', 'bam', 'bingo']
}
}
Step 2: from static JSON file to HTTP GET
- Install axios:
npm i axios
- Create a environment variable API_URL in the
config/prod.env.js
like the followingAPI_URL: '"https://api.stackexchange.com/2.2/"'
Create the file
api/questions.js
wich gonna contain all api calls dedicated to 'questions'// api/questions.js import axios from 'axios' /** * @param {string="vue"} search * @return {Promise<Object>} List of questions * @see {@link https://api.stackexchange.com/docs/search} * @see {@link https://api.stackexchange.com/docs/types/question} */ export function searchQuestions (search = 'vue') { return axios.get(`${process.env.API_URL}search?order=desc&sort=votes&intitle=${search}&site=stackoverflow`) }
- adapt code in
QuestionList.vue
Now the component'smounted () { searchQuestions('vue').then(response => { this.questions = response.data.items }) }
question
default property should be an empty array.
Note: Vue.js also support async functions!
async mounted () {
const questionsResponse = await searchQuestions('vue')
this.questions = questionsResponse.data.items
}
Solution
See: https://github.com/maxpou-slides/vue-workshop-app/compare/step-2...step-3