admin管理员组文章数量:1122846
I am just exploring VUE and trying to get the Posts from external API by using fetch. But while trying to get the value from ref, its showing as empty.
Here is what I have done so far.
<script setup>
import {onMounted, ref } from 'vue';
const Posts = ref([]);
onMounted( async () => {
const Url = '';
try {
const response = await fetch(Url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
Posts.value = await response.json();
}
catch(e) {
console.log(`Error: ${e}`)
}
})
console.log(Posts)
</script>
<template></template>
While to trying to console Posts, it is showing empty. I want to pass the value of Post to another component. But as it is showing empty here. I am clueless.
I am just exploring VUE and trying to get the Posts from external API by using fetch. But while trying to get the value from ref, its showing as empty.
Here is what I have done so far.
<script setup>
import {onMounted, ref } from 'vue';
const Posts = ref([]);
onMounted( async () => {
const Url = 'https://jsonplaceholder.typicode.com/posts';
try {
const response = await fetch(Url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}
Posts.value = await response.json();
}
catch(e) {
console.log(`Error: ${e}`)
}
})
console.log(Posts)
</script>
<template></template>
While to trying to console Posts, it is showing empty. I want to pass the value of Post to another component. But as it is showing empty here. I am clueless.
Share Improve this question edited Nov 21, 2024 at 10:19 NewUser asked Nov 21, 2024 at 10:01 NewUserNewUser 13.3k40 gold badges149 silver badges240 bronze badges 7- I think your console.log runs before the async operation is finished. If you console.log Posts.value inside the try block, after the await, it should work. Or you can use watch to see change in data after the fetch is done – fOURP Commented Nov 21, 2024 at 10:14
- Did you try to use the value the way you intended? – Estus Flask Commented Nov 21, 2024 at 10:17
- Currently it looks like a special case of this stackoverflow.com/questions/14220321/… – Estus Flask Commented Nov 21, 2024 at 10:19
- @fOURP then how can I pass the value to another component? – NewUser Commented Nov 21, 2024 at 10:21
- 1 Even right now you can probably use {{Posts}} in your HTML template and it 'll show your data. – fOURP Commented Nov 21, 2024 at 10:24
1 Answer
Reset to default 1First, read Lifecycle hooks.
The code inside <script setup>
runs when a new component instance has been created, before it is added to DOM.
The function passed to onMounted()
is run after the component has been added to DOM.
In short, you are requesting data at a later moment (mounted
) and expect it to have arrived at an earlier moment (setup
). Even if the data would arrive instantly (which it does not), Posts
would still be empty outside of onMounted()
.
Since you want to pass Posts
to another component, you have several options (I'll only explain the main ones). If the other component needing Posts
is a descendant of the current one, you could place it inside v-if="Posts.length"
and pass :posts="Posts"
to it, as a prop:
<template v-if="Posts.length">
<child-component :posts="Posts" />
</template>
While this method works, when used extensively it creates prop drilling and, in general, is considered less than ideal.
The only scenario in which you should use props in Vue is when you want the child component to be pure (have no knowledge of the context in which it is being used), so it could be used in different contexts. In that case you want the child component to be "dumb" (have little to no dependencies on external modules, such as stores) and receive all the data it needs via props
.
A different approach is to use a store (state management module).
In a nutshell, the component fetches the posts, places them in the store and they become instantly available to any other component in your app. It also has the advantage of being able to only fetch Posts
if they haven't previously been fetched. Actually, it has many more advantages than just that (read why should I use Pinia).
If you go with a store, there are multiple solutions (vuex
, a reactive
object), but the recommended solution for state management in Vue is pinia.
本文标签: vuejsVue get data from refStack Overflow
版权声明:本文标题:vue.js - Vue get data from ref - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736311984a1934935.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论