大佬们帮忙看一个问题,关于Vue3 SSR onServerPrefetch生命周期的
我是想在该生命周期里调用接口获取数据然后直接在HTML里渲染,结果报错了
<script setup>
import { onMounted, onServerPrefetch, ref } from 'vue'
import dayjs from 'dayjs'
import { getDetail } from '../services/index'
const detailData = ref(null)
onServerPrefetch(async () => {
let res = await getDetail()
detailData.value = {
...res.data,
bgsjShow: dayjs(res.data.bgsj).format('YYYY年MM月DD日')
}
})
onMounted(async () => {
if (!detailData.value) {
let res = await getDetail()
detailData.value = {
...res.data,
bgsjShow: dayjs(res.data.bgsj).format('YYYY年MM月DD日')
}
}
})
</script>
<template>
<section id="page1">
<div class="banner">
<p>名称:{{ detailData.qymc }}</p>
<p>时间:{{ detailData.bgsj }}</p>
</div>
</section>
</template>
这是报错信息!!!
PS C:\Users\a1561\Desktop\aisino\demo\ssr\basic-vue> yarn serve:ssr
yarn run v1.22.21
$ node server/index.js --ssr
file:///C:/Users/a1561/Desktop/aisino/demo/ssr/basic-vue/server/index.js
C:\Users\a1561\Desktop\aisino\demo\ssr\basic-vue\server
start server: localhost:5173
[Vue warn]: Unhandled error during execution of serverPrefetch hook
at <IndexView onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > >
node:internal/process/promises:288
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "connect ECONNREFUSED ::1:80".] {
code: 'ERR_UNHANDLED_REJECTION'
}
Node.js v18.19.1
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
我查看了Vue文档SSR的章节https://cn.vuejs.org/guide/scaling-up/ssr.html#component-life...,并没有找到问题所在,甚至连示例都一致。
提示很明显了,你把这个调用用try catch 包起来,大概率这个接口在服务端请求时报错了