【问题标题】:useFetch in onMounted not fetching data on direct link open nuxt3onMounted 中的 useFetch 未在直接链接打开 nuxt3 上获取数据
【发布时间】:2022-07-21 18:49:30
【问题描述】:

我正在使用useFetch来获取组合api中的数据,然后在组件中调用onMounted钩子中的函数,这是代码。

useShows.ts(可组合)

export function useShows(){

    var shows = useState<Show[]>('shows')

    const fetchShows = async() => {
        const {data, pending} = await useFetch<Show[]>('http://localhost:3000/shows')
        shows.value = data.value
    }

    return {shows, fetchShows}
}

shows.vue

<script setup lang="ts">

    var { shows, fetchShows } = useShows()

    onMounted(() => {
        console.log("On mounted called")
        fetchShows()
    })
</script>

<template>
    <div>{{shows}}</div>
</template>

当我从主页导航到/shows 时,它工作正常,但是当我直接打开链接localhost/shows 时,它不起作用,只给我一个空值。

【问题讨论】:

    标签: vue.js vue-composition-api nuxtjs3


    【解决方案1】:

    我也有同样的问题。我通过将它包装在 nextTick 中来解决它。

    await nextTick(async () => {
      await fetchShows()
    })
    

    【讨论】:

      猜你喜欢
      • 2022-11-10
      • 2023-02-04
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多