Files
vue-ts-example/src/pages/data-loaders.[id].vue
严浩 078cb2c0e9
Some checks failed
CI / build-and-deploy (push) Failing after 1m26s
/ depcheck (push) Successful in 1m35s
ESLint9
2024-10-11 18:03:03 +08:00

68 lines
1.9 KiB
Vue

<script lang="ts">
import { defineBasicLoader } from 'unplugin-vue-router/data-loaders/basic';
// https://uvr.esm.is/data-loaders/rfc.html
export const usePageData = defineBasicLoader(
'DataLoadersId',
async (route, ...otherArgs) => {
console.log('[DefineLoaderFn]', 'otherArgs :>> ', otherArgs);
await new Promise((resolve) => setTimeout(resolve, 777));
return { idFromPreviousPage: route.params.id, someOtherData: 'someOtherData' };
},
{
lazy: false,
// - `immediate`: the data is committed as soon as it is loaded.
// - `after-load`: the data is committed after all non-lazy loaders have finished loading.
// - `immediate`:数据在加载后立即提交。
// - `after-load`:数据在所有非惰性加载器加载完成后提交。
commit: 'immediate',
},
);
</script>
<script setup lang="ts">
definePage({
meta: {
metaKey: 'metaValue',
},
});
const {
data: pageData, // the data returned by the loader
isLoading, // a boolean indicating if the loader is fetching data
error, // an error object if the loader failed
reload, // a function to refetch the data without navigating
} = usePageData();
watch(
pageData,
(pageDataVal) => {
const message = [`[watch]`, `pageDataVal :>> `, pageDataVal];
if (pageDataVal === undefined) {
// hot updated 会造成 pageDataVal 为 undefined
console.warn(message);
} else {
console.debug(message);
}
},
{ immediate: true },
);
</script>
<template>
<h1>Data Loaders</h1>
<div flex="~ row">
<button @click="$router.back()">Back</button>
<button @click="reload()">Reload</button>
</div>
<main>
<p v-if="isLoading">Loading...</p>
<template v-else-if="error">
<p>{{ error.message }}</p>
<button @click="reload()">Retry</button>
</template>
<template v-else>
<p>{{ pageData }}</p>
</template>
</main>
</template>