我能够在我的 js 文件中获取数据,但不能在我的 .vue 文件中获取数据
I'm able to get the data in my js file but not in my .vue file
我可以使用 fetch api(想要执行 fetch api 而不是 axios)并调出我的本地 api 和 console.log 数据来自我的 api.js 文件 -
export default {
async getData(){
await fetch(url+"campground")
.then(result => result.json())
.then(data => {
console.log(data) // [{id:123,name:"Shimla"},{id:124,name:"Manali"}]
return data
})
}
}
当我尝试在我的 Catalogue.vue 文件上执行此操作时出现问题。
<script>
import api from '../api';
export default {
name: 'Catalogue',
data() {
return {
camps: null
}
},
methods: {
},
created() {
this.camps = api.getData()
console.log(this.camps) //Promise { <state>: "pending" }
},
}
</script>
我得到的结果通常是
Promise { : "pending" }
我该如何继续?谢谢
您不会 return 从 getData 获取任何内容,并且因为 fetch 是异步的,所以您不需要在其上放置 async/await。
改为
export default {
getData(){
return fetch(url+"campground")
.then(result => result.json())
}
}
然后因为它的return值是一个promise,你需要等待它(正如其他人所说)
async created() {
try {
this.camps = await api.getData()
} catch {
this.camps = []
}
},
或
created() {
api.getData().then(result => this.camps = result).catch(e => this.camps = [])
},
顺便说一句,如果 camps
从结果中以数组形式结束,您应该将其定义为数据中的空数组,而不是 null
.
我可以使用 fetch api(想要执行 fetch api 而不是 axios)并调出我的本地 api 和 console.log 数据来自我的 api.js 文件 -
export default {
async getData(){
await fetch(url+"campground")
.then(result => result.json())
.then(data => {
console.log(data) // [{id:123,name:"Shimla"},{id:124,name:"Manali"}]
return data
})
}
}
当我尝试在我的 Catalogue.vue 文件上执行此操作时出现问题。
<script>
import api from '../api';
export default {
name: 'Catalogue',
data() {
return {
camps: null
}
},
methods: {
},
created() {
this.camps = api.getData()
console.log(this.camps) //Promise { <state>: "pending" }
},
}
</script>
我得到的结果通常是
Promise { : "pending" }
我该如何继续?谢谢
您不会 return 从 getData 获取任何内容,并且因为 fetch 是异步的,所以您不需要在其上放置 async/await。
改为
export default {
getData(){
return fetch(url+"campground")
.then(result => result.json())
}
}
然后因为它的return值是一个promise,你需要等待它(正如其他人所说)
async created() {
try {
this.camps = await api.getData()
} catch {
this.camps = []
}
},
或
created() {
api.getData().then(result => this.camps = result).catch(e => this.camps = [])
},
顺便说一句,如果 camps
从结果中以数组形式结束,您应该将其定义为数据中的空数组,而不是 null
.