为什么serverPrefetch效果丢失了?

问题描述 投票:0回答:1

为什么第二个

console.log
的第二个报价值为空?

import {ref, onServerPrefetch, onMounted, inject} from 'vue';

const axios = inject('axios');
const route = inject('route');
const offer = ref(null);

const fetchOffer = async () => {
    try {
        const {data} = await axios(
            route('api.offer')
        );

        return data;
    }
    catch (e) {
        console.warn(e);
    }
}

onServerPrefetch(async () => {
    offer.value = await fetchOffer();
    console.log('after fetch on server', offer.value) // offer is not null
});

onMounted(async () => {
    if (!offer.value) {
        console.log('fetch on mount', offer.value) // offer value is null! How?!
        offer.value = await fetchOffer();
    }
});
vue.js vue-component vuejs3 server-side-rendering inertiajs
1个回答
0
投票

SSR 未向客户端提供简单的 vue 状态。

您可以通过创建可组合的

usePrefetchState
作为 Pinia 商店模块来解决问题。

下面是非常原始的例子:

// setup script or external composable

const { prefetchState, setPrefetchState } = usePrefetchState();
const items = ref<any>(prefetchState?.items ?? {});

// on server prefetch
onServerPrefetch(async () => {
  const response = await loadData();

  items.value = response.data;

  setPrefetchState({
    items: unref(items),
  });
});

// on client mounted
onMounted(async () => {
  if (!prefetchState) {
    const response = await loadData();

    items.value = response.data;
  }
});

重要提示:您的应用程序必须配置为从 SSR 向客户端提供 Pinia 状态https://pinia.vuejs.org/ssr/

© www.soinside.com 2019 - 2024. All rights reserved.