The following vue app should get some data from a firebase instance using the fetch method and display the data on the page.
UserExperiences.vue
JavaScript
x
43
43
1
<script>
2
import SurveyResult from './SurveyResult.vue';
3
//import axios from 'axios';
4
5
export default {
6
components: {
7
SurveyResult,
8
},
9
data() {
10
return{
11
results: []
12
}
13
},
14
methods:{
15
loadExperiences() {
16
fetch('https://***.firebaseio.com/surveys.json')
17
//axios.get('https://***.firebaseio.com/surveys.json')
18
.then((response) => {
19
if(response.ok) {
20
return response.json();
21
}
22
})
23
.then((data) => {
24
const results = [];
25
for (const id in data) {
26
results.push({
27
id: id,
28
name: data[id].name,
29
rating: data[id].rating
30
});
31
}
32
this.results = results;
33
});
34
},
35
},
36
};
37
// mounted(){
38
// axios.get('https://***.firebaseio.com/surveys.json').then(response => {
39
// this.results = response.data;
40
// })
41
// },
42
</script>
43
SurveyResult.vue
JavaScript
1
20
20
1
<template>
2
<li>
3
<p>
4
<span class="highlight">{{ name }}</span> rated the learning experience
5
<span :class="ratingClass">{{ rating }}</span>.
6
</p>
7
</li>
8
</template>
9
10
<script>
11
export default {
12
props: ['name', 'rating'],
13
computed: {
14
ratingClass() {
15
return 'highlight rating--' + this.rating;
16
},
17
},
18
};
19
</script>
20
The data renders on the webpage correctly on the webpage using the fetch method. Is there a way to use axios.get instead? I’ve tried using the mounted vue property and it gets the data to appear on a blank screen in a json format, but I want the data to render on the webpage with the stylings and other vue components together.
This is what the page should look like for context:
Advertisement
Answer
As long as you do the same transformation of the result (your results.push({ ... })
part), you should get the same result.
You can simplify it like this
JavaScript
1
6
1
axios.get("https://***.firebaseio.com/surveys.json")
2
.then(({ data }) => {
3
this.results = Object.entries(data).map(([ id, { name, rating } ]) =>
4
({ id, name, rating }));
5
});
6