zhangyuang / ssr

A most advanced ssr framework support React17/React18/Vue2/Vue3 on Earth that implemented serverless-side render specification.
http://doc.ssr-fc.com/
MIT License
2.61k stars 284 forks source link

请问如何在 layout/index.vue 里面拿到 fetchData #90

Closed simuusang closed 3 years ago

simuusang commented 3 years ago

按着文档上面通过props获取到的 fetchData是一个空对象

zhangyuang commented 3 years ago

给复现,按文档来就行

zhangyuang commented 3 years ago

fetch.ts 中 return value

props.asyncData 拿到 layout fetch 与 page fetch 的合并结果

props.fetchData 拿到当前fetch,layout fetch 或者 page fetch 的结果

simuusang commented 3 years ago

@zhangyuang 感谢您的回复,按照您说的我试了一下在layout/index.vue中还是获取不到fetchData,在fetch.ts里面返回value只能获取到 asyncData的值

layout/App.vue 代码如下

<template>
  <router-view :fetchData="fetchData" />
</template>

<script lang="ts">
import { Button } from "vant";
// 在这里可以进行一些全局组件的注册逻辑
export default {
  props: ["fetchData"],
  name: "AlphaApp",
  components: {
    Button,
  },
  setup(props) {
    console.log("layout/App.vue --------> fetchData", props.fetchData);
  },
  created() {
    const app = window.__VUE_APP__;
    app.use(Button);
  },
};
</script>

layout/index.vue 代码如下

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Layout",
  props: ["fetchData", "asyncData"],
  setup(props) {
    console.log("layout/index.vue --------> fetchData", props.fetchData);
    console.log("layout/index.vue --------> asyncData", props.asyncData);
  },
});
</script>

pages/index/fetch.ts

export default async (
  { store, router },
  ctx?: ISSRContext<{
    apiService?: IApiService;
  }>
) => {
  const data = __isBrowser__
    ? await (await window.fetch("/api/index")).json()
    : await ctx?.apiService?.index();
  await store.dispatch("indexStore/initialData", { payload: data });
  return data;
};

输出结果 image

zhangyuang commented 3 years ago

那是因为你根本就没有 layout/fetch 啊。。

simuusang commented 3 years ago

好的 谢谢解答我明白了