nuxt3 useFetch 刷新或首次进入报错
从其他页面跳转过来正常,但是刷新会报错
<script lang="ts" setup> const positionOption = ref([]); const initData = () => { useFetch('/api/getTagsByKey', { query: { tagKey: 'position' }, method: 'get', }).then(res => { positionOption.value = res.data.value.data; }) } initData(); </script>
解决方法:添加 await nextTick(),但是这个方法会导致客户端请求
<script lang="ts" setup> const positionOption = ref([]); const initData = async () => { await nextTick(); useFetch('/api/getTagsByKey', { query: { tagKey: 'position' }, method: 'get', }).then(res => { positionOption.value = res.data.value.data; }) } initData(); </script>
服务端请求方法:useFetch在最外层,不要放到方法中
<script lang="ts" setup> const positionOption = ref([]); useFetch('/api/getTagsByKey', { query: { tagKey: 'position' }, method: 'get', }).then(res => { positionOption.value = res.data.value.data; }) </script>