[英]Using Axios instead of fetch for http get requests with Vue App
The following vue app should get some data from a firebase instance using the fetch method and display the data on the page.以下 vue 应用程序应该使用 fetch 方法从 firebase 实例获取一些数据并将数据显示在页面上。
UserExperiences.vue用户体验.vue
<script>
import SurveyResult from './SurveyResult.vue';
//import axios from 'axios';
export default {
components: {
SurveyResult,
},
data() {
return{
results: []
}
},
methods:{
loadExperiences() {
fetch('https://***.firebaseio.com/surveys.json')
//axios.get('https://***.firebaseio.com/surveys.json')
.then((response) => {
if(response.ok) {
return response.json();
}
})
.then((data) => {
const results = [];
for (const id in data) {
results.push({
id: id,
name: data[id].name,
rating: data[id].rating
});
}
this.results = results;
});
},
},
};
// mounted(){
// axios.get('https://***.firebaseio.com/surveys.json').then(response => {
// this.results = response.data;
// })
// },
</script>
SurveyResult.vue调查结果.vue
<template>
<li>
<p>
<span class="highlight">{{ name }}</span> rated the learning experience
<span :class="ratingClass">{{ rating }}</span>.
</p>
</li>
</template>
<script>
export default {
props: ['name', 'rating'],
computed: {
ratingClass() {
return 'highlight rating--' + this.rating;
},
},
};
</script>
The data renders on the webpage correctly on the webpage using the fetch method.使用 fetch 方法在网页上正确呈现数据。 Is there a way to use axios.get instead?
有没有办法改用 axios.get? 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.
我已经尝试使用已安装的 vue 属性,它使数据以 json 格式显示在空白屏幕上,但我希望数据与样式和其他 vue 组件一起呈现在网页上。
This is what the page should look like for context:这是页面在上下文中的样子:
As long as you do the same transformation of the result (your results.push({... })
part), you should get the same result.只要您对结果(您的
results.push({... })
部分)进行相同的转换,您就应该得到相同的结果。
You can simplify it like this你可以像这样简化它
axios.get("https://***.firebaseio.com/surveys.json")
.then(({ data }) => {
this.results = Object.entries(data).map(([ id, { name, rating } ]) =>
({ id, name, rating }));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.