SSR

131 阅读1分钟

Vite Vue3 Pinia

修改baseURL

VITE_APP_API_URL='localhost:3000/api/'

接口请求会报错,host会是::1 的问题,因此要加上localhost:3000,指定具体的host

pinia 请求数据需要await

<script setup> 
const store = useStore() 
onServerPrefetch(async () => {
  // ✅ this will work
  await store.fetchData() 
})
</script>

fetchData 也需要 await

<script lang="ts">
export default {
  // @ts-ignore
  asyncData({store, router}) {
    return store.dispatch('/FETCH_LIST', {
      parma1: 'xxx', 
    })
  }
}
</script>

页面重复渲染问题

store的数据,在vue文件中引用时,使用computed或者响应式解构来定义变量

const testStore = useTestStore();
const data = computed(()=> testStore.data);

预取数据问题

在客户端路由跳转中,会出现数据未请求的情况,需要预取数据 Vue3 Vuex中

// entry-client.js
// css problem when use router.before effect

router.afterEach((to, from) => {
    // 客户端直接访问页面走服务端渲染,客户端不用发请求;
    // 反之从客户端其他页面进入,客户端需要发请求
    // 通过路由from参数判断
    getAsyncData(router, store, from?.name)
})

改造BOM DOM

// 判断客户端
export const isPhone = (): boolean | null => {
  if (import.meta.env.SSR) {
    return null;
  }
  return /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator?.userAgent);
};

改造a img标签

将跳转用a标签代替 完善img alt属性